我為我的新專案選擇了 prisma2 作為 ORM。
我遇到一個考慮,我怎么能加載關系的關系?
例如我有這樣的表定義:
model Brand {
id Int @id @default(autoincrement())
name String @unique
addedBy User @relation(fields: [userId], references: [id])
userId Int
models Model[]
}
model Model {
id Int @id @default(autoincrement())
name String
addedBy User @relation(fields: [userId], references: [id])
userId Int
Brand Brand? @relation(fields: [brandId], references: [id])
brandId Int?
Car Car[]
}
model Car {
id Int @id @default(autoincrement())
plateCode String
vinCode String @unique
addedBy User @relation(fields: [userId], references: [id])
userId Int
ownedByCompany Company @relation(fields: [companyId], references: [id])
companyId Int
model Model @relation(fields: [modelId], references: [id])
modelId Int
year Int
acquiredDate DateTime
insuranceValidFrom DateTime
insuranceExpiresOn DateTime
technicalInspectionValidFrom DateTime
technicalInspectionExpiresOn DateTime
}
當我想檢索我的資料時,我收到了以下回復:
[
{
"id": 1,
"plateCode": "XXQ:000",
"vinCode": "ZXQQQQQQQQQQQQQQQQQQQ",
"userId": 1,
"companyId": 1,
"modelId": 1,
"year": 2004,
"acquiredDate": "2021-12-15T21:02:57.206Z",
"insuranceValidFrom": "2020-02-01T21:02:57.206Z",
"insuranceExpiresOn": "2023-02-01T21:02:57.206Z",
"technicalInspectionValidFrom": "2021-06-25T21:02:57.206Z",
"technicalInspectionExpiresOn": "2023-06-25T21:02:57.206Z",
"model": {
"id": 1,
"name": "525i",
"userId": 1,
"brandId": 1
}
}
]
有沒有辦法用包含物件以類似的方式填充brandId?或者也許我可以在模式定義中定義虛擬/計算欄位?
我知道我可以通過第二次呼叫 db 來轉換/填充該欄位,但只是想是否有一種方便的方法可以做到這一點。任何幫助,將不勝感激。:)
uj5u.com熱心網友回復:
只需include用于每個關系,就像這樣:
prisma.car.findMany({
include: {
model: {
include: {
Brand: true,
},
},
},
});
檔案中的更多資訊
如果您只想要一些欄位,而不是所有欄位,那么您可以select以相同的方式使用。雖然你不能混合它們。
注意:您的Brand欄位以大寫開頭,您可能希望將其修復為一致
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412267.html
標籤:
