I am using prisma + mysql (on planetscale). When I link two items that are in different tables, I normally use connect
or disconnect
:
const getUser = await prisma.user.update({
where: {
id: 9
},
data: {
posts: {
| connect: {
| id: 11
| },
create: {
title: "My new post title"
}
}
}
})
I am wondering whether that's necessary or why that's necessary?
I also noticed that I can just update records in my database by updating the id (as a plain string), and it will still work. e.g.:
// example for updating a one-to-many relationship:
const getUser = await prisma.user.update({
where: {
id: 9
},
data: {
postId: "123192312i39123123"
}
}
})
... or if it's an explicit many-to-many relation, I can just edit the row in the relation-table & update the id.
Is this a bad way of doing things? Am I going to break something later down the line in doing it this way?
While you can manually update IDs, using
connect
anddisconnect
has a few advantages:First and foremost,
connect
throws an exception if any of the connected records do not exist.Because Prisma supports multiple DBs, I assume they do this check in their own engine, rather than relying on the DB to check the foreign key constraint.
It can be used to update a specific entity plus one-to-one, one-to-many and many-to-many relationships with a single interface and without having to write a separated query for the junction table:
You can also use
connectOrCreate
to easily create an entity if it doesn't exist already.For
disconnect
, you also have single interface that works with one-to-one, one-to-many and many-to-many relationships, and you can easily disconnect all related records too:You can read more in the officials docs.