How to handle relations during insert?

Is this correct? Feels like I should be able to do it in one call, but values doesn't accept anything else
const group = await db
.insert(groups)
.values({ name: inputs.name })
.returning();
await db.insert(usersToGroups).values({
groupId: group[0]!.id,
userId: session.user.id,
});
const group = await db
.insert(groups)
.values({ name: inputs.name })
.returning();
await db.insert(usersToGroups).values({
groupId: group[0]!.id,
userId: session.user.id,
});
3 Replies
Louistiti
Louistiti15mo ago
I think you should use db transactions to do that https://orm.drizzle.team/docs/transactions
benjick
benjickOP15mo ago
@louistiti_ thanks, changed it to that 👍 But now I wonder, how do I query based on relation data?
await db.query.groups.findMany({
with: {
users: {
where: eq(usersToGroups.userId, session.user.id),
},
},
});
await db.query.groups.findMany({
with: {
users: {
where: eq(usersToGroups.userId, session.user.id),
},
},
});
this still gives me groups which doesn't match the relation I guess this works
await db.query.usersToGroups.findMany({
where: eq(usersToGroups.userId, session.user.id),
with: {
group: true,
},
});
await db.query.usersToGroups.findMany({
where: eq(usersToGroups.userId, session.user.id),
with: {
group: true,
},
});
Louistiti
Louistiti15mo ago
let me find an example in may codebase
return this.db.query.products.findMany({
where: () => eq(products.shop_id, shopId),
with: {
imagesToProduct: {
columns: {
image_id: true,
},
with: {
image: {
columns: {
url: true,
},
},
},
},
variants: true,
informations: true,
logistics: true,
},
});
return this.db.query.products.findMany({
where: () => eq(products.shop_id, shopId),
with: {
imagesToProduct: {
columns: {
image_id: true,
},
with: {
image: {
columns: {
url: true,
},
},
},
},
variants: true,
informations: true,
logistics: true,
},
});
This should be the good way to go !
Want results from more Discord servers?
Add your server