Hi @nicolas-goudry 👋
Thank you for raising this question.
Using an explicit many-to-many relation instead of an implicit one can make the Prisma Client API more complex. However, the advantage of using explicit many-to-many relations is that you can define extra fields on the relation table, which can be useful for storing additional information about the relation.
In your case, you're now connecting Pet to Owner through the OwnersOfPets model, which requires you to specify the petId and ownerId in the connect clause. This is why you can't use the unique name field of Owner to connect to the Pet anymore, because the connection is now being managed through the OwnersOfPets model. While the developer experience (DX) might be different when using explicit many-to-many relations compared to implicit ones, this is the expected behavior and not something you're doing wrong.
If this answers your question, it would be great if you could mark this Discussion as answered to indicate that it has been resolved.
Otherwise please let us know how else we can help you further or close the Discussion if it was resolved in some other way 🙏
Relations handling with explicit many to many relation
typescript - Prisma many-to-many relations: create and connect - Stack Overflow
database design - Struggling with Prisma schema setup for many-to-many relationships on MongoDB - Stack Overflow
mysql - Prisma many to many relation - Stack Overflow
What you need here is connectOrCreate.
So something like this should work:
await prisma.post.create({
data: {
title: 'Hello',
categories: {
create: [
{
category: {
create: {
name: 'category-1',
},
},
},
{ category: { connect: { id: 10 } } },
],
},
},
});
You can also read more about this in the docs here
After hours of trying I finally came up with the following solution for my use case.
park[] <-> exercise[]
// create parks
const parks = await prisma.park.createMany({data: [...]});
// create and connect exercises
const exercises = [...];
await Promise.all(
exercises.map(async (exercise) => {
await prisma.exercise.create({
data: <any>{
...exercise,
parks: {
connect: parks.map((park) => ({ id: park.id })),
},
},
});
}),
);