[英]How do i store custom object in prisma schema?
我有一個名為“設置”的模型
model Setup {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String? @unique @db.ObjectId
user User? @relation(fields: [userId], references: [id])
contract String[]
legal String[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
在這個模型中,我想存儲一個數組
const contractData = {
id: '729a4839f3dapob44zt2b4b1',
name: 'Example Name',
text: 'Example Text'
}
所以在我上面的模型“設置”中,我想存儲合同數據
prisma.setup.create({
data: {
userId: '6399bc74426f71f2da6e316c',
personal: [],
contract: contractData,
legal: []
}
})
不幸的是,這行不通。
我如何為合同定義一個對象並將其存儲在我的數據庫中?
如果您想存儲原始 JSON,請查看本指南: https ://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields
您將希望在 Prisma 中使用Json
以便能夠存儲原始 JSON 對象(或多個 JSON 對象作為數組。)
model Setup {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String? @unique @db.ObjectId
user User? @relation(fields: [userId], references: [id])
contract Json[]
legal String[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
您的 Prisma prisma.setup.create
查詢基本上是完全相同的。 請注意,查詢此 JSON 中的內容會比較棘手 - 我建議創建一個新模型,然后將其連接到Setup
模型,但如果這不是一個選項,您仍然可以在contract
字段上執行一些有限的查詢。
文檔: https ://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filter-on-a-json-field
為了在合同字段中存儲對象,您需要將合同字段的類型從 String[] 更改為 Object[]。
model Setup {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String? @unique @db.ObjectId
user User? @relation(fields: [userId], references: [id])
contract Object[]
legal String[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
在合同字段中存儲一個對象,例如
prisma.setup.create({
data: {
userId: '6399bc74426f71f2da6e316c',
personal: [],
contract: [contractData],
legal: []
}
})
contract
字段現在是一個數組,因此您需要將對象作為數組的元素傳遞,例如[contractData]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.