我正在使用 Prisma 3.7.0 和 Postgresql 13。我需要在具有一些附加数据的两个模型之间创建多对多关系,但我不知道如何在 Prisma 模式中执行此操作。我想要添加的字段未正确添加到任一表中。
这里有一些简化的(人为的)SQL 来说明目标:
这在 SQL 中非常简单,但我从 Prisma 文档中不太明白如何做到这一点。
CREATE TABLE animal (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL -- e.g. "tiger" or "armadillo"
)
CREATE TABLE animal_bodyparts (
animal INT,
bodypart INT,
-- I want to add these two fields to the relation.
count INT, -- How many of this bodypart the animal has
is_vital BOOLEAN, -- Does the creature die if this part is damaged?
PRIMARY KEY (animal, bodypart)
CONSTRAINT fk_animal FOREIGN KEY (animal) REFERENCES animal(id),
CONSTRAINT fk_bodypart FOREIGN KEY (bodypart) REFERENCES bodypart(id)
)
CREATE TABLE bodypart (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL -- e.g. "head" or "leg"
)
这是迄今为止我能用 Prisma 找到的最好的结果:
model Animal {
id Int @id @default(autoincrement)
name String // e.g. "tiger" or "armadillo"
parts BodyPart[]
}
model BodyPart {
id Int @id @default(autoincrement)
name String // e.g. "head" or "leg"
animals Animal[]
}
但是我应该将 count
和 is_vital
列放在 Prisma 模型中的哪里?我发现在一对多关系中,有某种方法可以通过 @relation
标记添加一些信息,但我不认为它可以满足这一需求。 p>
最佳答案
您可以按如下方式进行:
datasource mysql {
provider = "mysql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
generator erd {
provider = "prisma-erd-generator"
output = "entity-relationship-diagram.svg"
}
model Animal {
id Int @id @default(autoincrement())
name String
animalAndBodyParts AnimalAndBodyParts[] @relation()
}
model AnimalAndBodyParts {
id Int @id @default(autoincrement())
count Int
isVital Boolean @map("is_vital")
animal Animal @relation(fields: [animalId], references: [id])
animalId Int
bodyPart BodyPart @relation(fields: [bodyPartId], references: [id])
bodyPartId Int
}
model BodyPart {
id Int @id @default(autoincrement())
name String
animalAndBodyParts AnimalAndBodyParts[] @relation()
}
它将生成一个数据库,如图所示:
您可以通过以下方式保存数据:
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const saveData = async () => {
const animal = await prisma.animal.create({
data: {
name: 'Lion',
animalAndBodyParts: {
create: {
count: 2,
isVital: true,
bodyPart: {
create: {
name: 'Eye',
},
},
},
},
},
include: {
animalAndBodyParts: {
include: {
bodyPart: true,
},
},
},
})
console.log(JSON.stringify(animal, null, 2));
}
saveData()
数据将如下图所示
关于database - 如何在 Prisma 模式中表示额外的关系列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70491963/