kysely-org / kysely

A type-safe typescript SQL query builder
https://kysely.dev
MIT License
10.33k stars 262 forks source link

What's the best way of doing conditional joins? #575

Closed nicholasgriffintn closed 1 year ago

nicholasgriffintn commented 1 year ago

Hey,

I've found the docs on relations that suggest to do joins like this:

const persons = await db
  .selectFrom('person')
  .selectAll('person')
  .select((eb) => [
    withPets(eb),
    withMom(eb)
  ])
  .execute()

I'm wondering, what would be the best way to do the joins conditionally?

Basically, I only want to join X if the matching param is provided. Sorry if that's super simple and I've missed it in the docs somewhere :)

koskimas commented 1 year ago

Those don't actually create joins but subqueries. But I'm guessing by joins, you mean fetching related items as nested objects/lists? Probably the easiest way to do that conditionally is to use the $if method: https://kyse.link/?p=s&i=oveFTLrzoDsQFAqRrD4O

koskimas commented 1 year ago

There's a recipe on the subject https://kysely.dev/docs/recipes/conditional-selects.

nicholasgriffintn commented 1 year ago

Ahhh I see! That makes sense thanks :)