-
Let's say we have This could be implemented like with this model User {
id String @default(cuid()) @id
organisation Organisation @relation("OrgMembers", fields: [orgId], references: [id])
orgId String
Organisation Organisation[] @relation("Owner")
}
model Organisation {
id String @default(cuid()) @id
User User[] @relation("OrgMembers")
owner User @relation("Owner", fields: [ownerId], references: [id])
ownerId String
} How to create a new pair of As we realized #3483, this could not be made by the nested writes. Because of "NOT NULL" constraints for both relations, this issue looks similar to the chicken-egg problem. But we can use the Transaction API and create both records in one transaction. But one more thing before that – we also have to tweak the time when foreign constraints are actually checked. Just like that: ALTER TABLE "public"."Organisation"
ALTER CONSTRAINT "Organisation_ownerId_fkey" DEFERRABLE INITIALLY DEFERRED
ALTER TABLE "public"."User"
ALTER CONSTRAINT "User_orgId_fkey" DEFERRABLE INITIALLY DEFERRED And now let's try to create both const userId = cuid();
const orgId = cuid();
const writeUser = prisma.user.create({
data: {
id: userId,
organisation: {
connect: {
id: orgId,
}
}
}
});
const writeOrg = prisma.organisation.create({
data: {
id: orgId,
owner: {
connect: {
id: userId
}
}
}
});
await ctx.db.$transaction([writeUser, writeOrg]); Expected Result: both records created. Actual Result: the And the error:
Question: – is there is a way to deal with this case without falling to using raw SQL? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @yarikos 👋 It would be great if you could create a feature request here with the above use case especially for deferreble constraints :) |
Beta Was this translation helpful? Give feedback.
Hey @yarikos 👋
Yes I think the required inter-dependency here would make it impossible to use in a Prisma transaction, so a transactional raw query would be the only way to go here.
It would be great if you could create a feature request here with the above use case especially for deferreble constraints :)