KyselyK
Kysely2y ago
tzezar

newbie need help with json_build_object

Hi! Just starting with kysely and encountered problem I cant solve. I want to build raw query with kysely builder...
  JSON_BUILD_OBJECT('id', unit.id, 'name', unit.name) AS unit

this part gives me trouble. I would be grateful for your help


        sql`
        SELECT 
            sku.id,
            JSON_BUILD_OBJECT('id', unit.id, 'name', unit.name) AS unit
        FROM sku
        LEFT JOIN unit ON unit.id = sku.stock_unit_id
        LIMIT 100;
    `


    let results = await kyselydb
        .selectFrom('sku')
        .leftJoin('unit as u', 'u.id', 'sku.stock_unit_id')
        .selectAll('sku')
        .select((eb) => [
            jsonObjectFrom(

            ).as('unit')
        ])
        .limit(10)
        .execute()
Solution
Here you go https://kyse.link/DqXNv

Note that the properties are nullable in the selected
unit
object because you're using left join. The types are correct. If you are sure there's a
unit
for each
sku
then use
innerJoin
instead.
Was this page helpful?