Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON Array of Column Values #1100

Open
prathikvel opened this issue Aug 4, 2024 · 1 comment
Open

JSON Array of Column Values #1100

prathikvel opened this issue Aug 4, 2024 · 1 comment
Labels
helpers Related to library's helpers mysql Related to MySQL question Further information is requested

Comments

@prathikvel
Copy link

prathikvel commented Aug 4, 2024

Hi there,

Is it possible to create a JSON array of column values in Kysely?

For example, this Kysely query...
const result = await db
  .selectFrom('person')
  .select((eb) => [
    'id',
    jsonArrayFrom(
      eb.selectFrom('pet')
        .select('pet.name')
        .whereRef('pet.owner_id', '=', 'person.id')
        .orderBy('pet.name')
      ).as('pets')
  ])
  .where('id', '=', 1)
  .executeTakeFirst()
...would result in nested data like this.
{
  "id": 1,
  "pets": [
    {
      "name": "Ace"
    },
    {
      "name": "Zuko"
    }
  ]
}

Is it possible to create a flat array like the following using Kysely?

{
  "id": 1,
  "pets": [
    "Ace",
    "Zuko"
  ]
}
This MySQL query would work, but I don't know how to implement it in Kysely.
select `person`.`id`, (
  select cast(coalesce(json_arrayagg(
    `agg`.`name`
  ), '[]') as json) from (
      select `pet`.`name`
      from `pet`
      where `pet`.`owner_id` = `person`.`id`
      order by `pet`.`name`
    ) as `agg`
  ) as `pets`
from `person`
where `person`.`id` = 1;

I looked for similar issues, but I only found #819, which is loosely related. Sorry if I missed something!

@igalklebanov igalklebanov added question Further information is requested mysql Related to MySQL helpers Related to library's helpers labels Aug 25, 2024
@thelinuxlich
Copy link
Contributor

Maybe you can create a helper similar to the one on the documentation: https://kysely.dev/docs/recipes/relations#the-json-data-type-and-functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
helpers Related to library's helpers mysql Related to MySQL question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants