Reputation: 447
I have the following prisma.schema
file for a small application where user accounts have a many to many relationship to skills. I am trying write a prisma query that accepts a list of skills and creates a new account and also either connects the skills to the user account if the skill exists, or creates the skill then connects it to the account if it does not exist.
model Account {
id Int @id @default(autoincrement())
skills SkillsOnAccounts[]
}
model Skill {
id Int @id @default(autoincrement())
name String
accounts SkillsOnAccounts[]
}
model SkillsOnAccounts {
skill Skill @relation(fields: [skillId], references: [id])
skillId Int
account Account @relation(fields: [accountId], references: [id])
accountId Int
@@id([skillId, accountId])
}
I am running into a few problems using connectOrCreate
.
prisma.account.create({
data: {
skills: {
create: skills.map((skill) => {
return {
skill: {
connectOrCreate: {
where: {
name: skill.value
},
create: {
name: skill.value,
},
},
},
}
}),
},
}
})
I am getting an error though,
Unknown arg `name` in data.skills.create.0.skill.connectOrCreate.where.name for type SkillWhereUniqueInput. Did you mean `id`? Available args:
type SkillWhereUniqueInput {
id?: Int
}
It seems like the only thing accepted in the connectOrCreate connect object is ID. I verified this, and it worked for me, but this seems counterintuitive. If I am using connectOrCreate, it is because I possibly do not have a record for that item yet. In this case, I may not have a skill persisted in the database, so I want to create it. Thus, I do yet have an ID. What is the point of using connectOrCreate if you already have IDs for everything you want to connect? You can just connect?
I would love tips on how to properly connectOrCreate when you do not have the ID. I want to be able to pass the skill name to connectOrCreate so it connects the skill with that name, or creates a new skill with that name.
Maybe because there is no guarantee that name is unique? If I add a constraint would that work?
Upvotes: 1
Views: 1426
Reputation: 447
The answer was that there was no guarantee that name was unique. Adding @unique
to the name field of the skill model fixed the issue!
Upvotes: 1