SQLite - one to many relationship, join only returning first match
Hi everyone 🙂 I'm having an issue with my select query using Drizzle + SQLite3.
In my DB, a content item can have many content parts.
Here's my simplified schema in
src/db/schema.ts
:
And here's my select. I'm trying to select the content items but join to include the content parts:
When I run this select, it only picks up the first matching contentPart:
But I can find multiple matching content parts when I run db.select().from(contentPartsTable).where(eq(contentPartsTable.contentItemId, contentItemId))
.
Is there a way to include the array of all matching 'content_parts' when I run the first select query?9 Replies
This is the perfect use case for the relational query builder
Ah ok, so SQL select doesn’t work the way I want it to?
And just confirming, the relational query builder works with SQLite and better-sqlite3? I tried adding some relations and couldn’t get it to work, but I might need to spend more time playing with it
I mean, you can make the select do whatever you want
So, by default, select will give the results in the same way the you're selecting it
In this case, the joined table is getting added to your query in the same rows as the main table
But you're only selecting the first row, that's why you're only seeing 1 item of the contant_parts
In this line:
Ah ok thanks for explaining that, so how would I get one content item, with all its content parts?
If you want you keep using the crud API, here is an example: https://orm.drizzle.team/docs/joins#aggregating-results
Joins [SQL] - Drizzle ORM
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
Ah ok I see, thanks! I will look more into the relational query builder. Do you know if the query builder is compatible with SQLite and better-sqlite3?
Yes it is
BTW, this is not the only option. You could do subqueries and and json aggregation, which basically what the RQB does for you
Ah ok, thanks for your help here! I might have a play with subqueries. I like the idea of staying a bit closer to SQL
After a bit of head scratching I got the query builder working properly this morning! I was missing the part where you add the schema to the main DB export. Thanks again for your help @Angelelz 🙂
I'll copy and paste in my code including the relations, in case anyone runs into the same issue
Great! Thank you for the report back