Replies: 2 comments
|
Call const [insertedMainItem] = await tx
.insert(mainItemTable)
.values(mainItem)
.returning(); // all columns, including auto-generated id
Same shape for upserts: const [upsertedMainItem] = await tx
.insert(mainItemTable)
.values(mainItem)
.onConflictDoUpdate({
target: mainItemTable.id,
set: { ...mainItem, updatedAt: new Date() },
})
.returning();Then use the returned id in the same transaction for the joined tables: await tx.insert(genresTable).values(
genres.map((g) => ({ ...g, mainItemId: insertedMainItem.id }))
);One gotcha worth flagging: this works on PostgreSQL and SQLite. MSSQL uses |
|
The clean pattern is: do all your writes, then do one relational read at the end of the same transaction using the query API. await db.transaction(async (tx) => {
const [main] = await tx.insert(mainItemTable).values(mainItem)
.onConflictDoUpdate({ /* ... */ })
.returning();
// ... your writes to genres / credits / joinTables here ...
const full = await tx.query.mainItemTable.findFirst({
where: eq(mainItemTable.id, main.id),
with: { genres: true, credits: true, similar: true, keywords: true },
});
return full; // fully nested, ids included, and consistent because it's still in the tx
});
(And yeah, |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Sorry if the title is not clear
Suppose a main item has a 1-to-n or n-to-n relationship with 5-6 other tables
in the same transaction, i write to the other tables and joinTables with new methods.
I currently call returning* to get back the primary key
* (from the docs for sqlite driver. theres another callback called
output()but i think thats exclusive to MSSQL?)however, i dont just want a subset of the saved data. i'd like the full object back with their primary ids in the original structure that it was provided. with a spread operator most likely
performing upsert-read cycles on every item or stitching together the sum of its parts seems like the only way?
please advise
Thank you
All reactions