typeorm icon indicating copy to clipboard operation
typeorm copied to clipboard

Using jsonb_array_elements with createQueryBuilder

Open ootkin opened this issue 7 years ago • 6 comments

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Hi guys,

Is there a way to use jsonb_array_elements with createQueryBuilder().

It doesn't work with from, because it want an Entity as first parameters.

ootkin avatar Feb 09 '19 15:02 ootkin

Maybe post your entity definition and SQL you want to run using query builder.

vlapo avatar Feb 10 '19 11:02 vlapo

This is a generic question, but I'll try to explain with an example.

Consider this entity:

@Entity()
class Store {
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column({ type: 'jsonb', name: 'time_tables'})
    timeTables: TimeTable[];
}

Where TimeTable is an interface defined like this:

interface TimeTable {
    day: number; //week day
    openings: Opening[];
}

interface Opening {
    from: string; //from opening time, e.g.: 10:00:00
    to: string; //to opening time, e.g.: 20:00:00
}

Now, i want to retrieve all the stores that are open in a specific time. So i need to iterate over my jsonb column.

Raw sql query would be:

SELECT DISTINCT *
FROM stores,
jsonb_array_elements(time_tables) time_table,
jsonb_array_elements(time_tables->'openings') openings,
WHERE
 ($1 BETWEEN CAST(openings ->> 'from' AS TIME) AND CAST(openings ->> 'to' AS TIME))
AND time_table ->> 'day' = $2

Where $1, $2 are parameter that specify a time ($1) and a week day ($2)

So, in order to iterate over my json, i need to unwind the 2 arrays and check if time parameter is between the opening (from and to) in a specified week day.

I don't want to retrieve raw results, so i want to use createQueryBuilder.

ootkin avatar Feb 11 '19 09:02 ootkin

Hi, any update about this case? thank you.

ignaion avatar Sep 17 '20 07:09 ignaion

You'll want to use the raw operator or query builder with where>

For other questions, please check out the community slack or check TypeORM's documentation page on other support avenues - cheers!

imnotjames avatar Oct 05 '20 06:10 imnotjames

@ignaion have you found a solution?

neekey avatar Apr 03 '21 04:04 neekey

@ignaion have you found a solution?

yap, I`m switched my project to sequelize

kalyuk avatar May 28 '21 08:05 kalyuk