我正在使用 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標簽添加一些資訊,但我認為它不能滿足這一需求。
uj5u.com熱心網友回復:
你可以這樣做:
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()
資料將如下圖所示

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/395480.html
上一篇:Magento2:從資料庫中獲取產品、Sku和制造商名稱
下一篇:是否可以將子彈放入v-for中?
