Inserting records into related tables
I have a few of tables that are related. I just need to know if there's a better approach when inserting records into these. I'm using PlanetScale so no FK constraints. Here's my approach.
Insert statements
I just need to know if there's a better approach to this? Instead of writing three, can we batch them?
6 Replies
Hi, i don't know if its a better approach, but you could predict the uniqueId in server-side, then make the three inserts.
This way you dont need to wait three responses
I see. Thanks for the suggestion @doiská
It gets a bit trickier when your payload is an array. Ex 👇 . Prisma has a way of nesting the inserts. Just wondering if I can do the same with Drizzle
No, you can't insert related rows in 1 query. It's not possible with SQL in general, so Prisma splits it into multiple inserts under the hood. Honestly, I'm unsure if there's a way to do this efficiently, so my best guess is to insert the products one by one and use the
insertId
field returned from the query. I suspect Prisma does something similar.Noted. Thanks @Dan Kochetov
I would advise using a transaction to insert related rows. If one insert fails, everything is rollback and no row is committed 😉
https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/mysql-core/README.md#transactions
https://github.com/planetscale/database-js#transactions
GitHub
drizzle-orm/README.md at main · drizzle-team/drizzle-orm
TypeScript ORM for SQL. Contribute to drizzle-team/drizzle-orm development by creating an account on GitHub.
GitHub
GitHub - planetscale/database-js: A Fetch API-compatible PlanetScal...
A Fetch API-compatible PlanetScale database driver - GitHub - planetscale/database-js: A Fetch API-compatible PlanetScale database driver