I have two models, Fish and BoardFish with a 1:1 relation - BoardFish is a type of Fish I created some seed Fish with named types.
how can I do this in Prisma? I think i have the schema setup, but inserting data isn't really documented apart from fancy/nested types.
schema:
model Fish {
name String @id
boardFish BoardFish[]
}
model BoardFish {
id Int @id @default(autoincrement())
name String
fishType Fish @relation(fields: [name], references: [name])
}
try to create:
let fishes = []
for (let c = 0; c < fishCount; c ) {
const fishType = await prisma.fish.findFirst({ where: { name: 'salmon' } })
const fishData = {
fishType: fishType!.name,
// name: 'salmon',
px: 0,
py: 0,
}
const fish = await prisma.boardFish.create({ data: fishData })
fishes.push(fish)
}
but I'm unable to do the insertion:
→ 35 const fish = await prisma.boardFish.create({
data: {
fishType: 'salmon',
~~~~~~~~
px: 3,
py: 5
}
})
Argument fishType: Got invalid value 'salmon' on prisma.createOneBoardFish. Provided String, expected FishCreateNestedOneWithoutBoardFishInput:
type FishCreateNestedOneWithoutBoardFishInput {
create?: FishCreateWithoutBoardFishInput | FishUncheckedCreateWithoutBoardFishInput
connectOrCreate?: FishCreateOrConnectWithoutBoardFishInput
connect?: FishWhereUniqueInput
}
The types involved are pretty hard to follow, Prisma seems to really take the cake for most "magic" with thousands of lines of auto generated code, which I've been digging through without much luck.
CodePudding user response:
If you want to have 1:1 relations, I think the schema needs to look more like this:
model Fish {
name String @id
boardFish BoardFish? // removed autogenerated `[]` and made optional
}
model BoardFish {
id Int @id @default(autoincrement())
name String
fishType Fish @relation(fields: [name], references: [name])
}
When creating a related record, use prisma's connect api
const fish = await prisma.boardFish.create({
data: {
fishType: {
connect: { name: 'salmon' }, // or `connectOrCreate` if it doesn't exist
},
}
})