There's two errors in the code.
Tag.name field is not unique
From what I can infer from your domain, two tags should not have the same name. Furthermore, since the name field is not unique, you can't use it by itself to uniquely identify a specific Tag record and so Prisma will complain if you try to pass only the name field in the where condition of connectOrCreate.
The simplest and logical solution to this is to make the name field unique. Here's your updated Tag model
model Tag {
id Int @id @default(autoincrement())
name String @unique // change
articles Article[]
}
Incorrect syntax for connectOrCreate
You're passing separate arrays to the where and create fields. Instead, when you want to connect/create multiple records, pass an array of objects to connectOrCreate each with its own where and create field. Here's an example from the Prisma Docs that shows how to use connectOrCreate with multiple records.
This is what your create query should look like:
await prisma.article.create({
data: {
title,
summary,
link,
archive,
content,
image,
tags: {
connectOrCreate: tags.map((tag) => {
return {
where: { name: tag },
create: { name: tag },
};
}),
},
},
});
Answer from Tasin Ishmam on Stack OverflowHow to use connectOrCreate with many to many
differences between connectOrCreate and upsert?
Use connectOrCreate for nested fields and relationships.
connectOrCreate multiple records issue
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 })),
},
},
});
}),
);