多对多关系 prisma
Many to many relations prisma
我是后端和东西的新手。
我有两个模型:产品和城市。城市可以有很多产品,产品可以有很多城市,所以我创建了另一个 table ProductsOnCities:
model City {
id Int @id @default(autoincrement())
name String
pickupPoints PickupPoint[]
products ProductsOnCities[]
}
model Product {
id Int @id @default(autoincrement())
title String
price Int
cities ProductsOnCities[]
}
model ProductsOnCities {
city City @relation(fields: [cityId], references: [id])
cityId Int
product Product @relation(fields: [productId], references: [id])
productId Int
@@id([cityId, productId])
}
现在如何插入数据?例如,我想创建包含 4 个产品的城市(我的数据库中已经存在),我真的需要在那里创建 4 个对象,如 prisma docs 所示吗?以下是文档中的示例。
const assignCategories = await prisma.post.create({
data: {
title: 'How to be Bob',
categories: {
create: [
{
assignedBy: 'Bob',
assignedAt: new Date(),
category: {
connect: {
id: 9,
},
},
},
{
assignedBy: 'Bob',
assignedAt: new Date(),
category: {
connect: {
id: 22,
},
},
},
],
},
},
})
我就是这么做的:
const assignCategories = await prisma.city.create({
data: {
name: 'Toronto',
products: {
create: [
{
product: {
connect: {
id: 1
},
},
},
{
product: {
connect: {
id: 15
},
},
},
{
product: {
connect: {
id: 11
},
},
},
{
product: {
connect: {
id: 18
},
},
},
],
},
},
})
它工作得很好,但是有什么方法可以更简洁地做到这一点吗?我真的需要为我添加的每个产品传递一个新的“大”对象吗?我尝试将产品 ID 数组传递给连接,但它不起作用。
是的,您在使用 explicit many-to-many relations 时需要以这种方式传递它。
您可以将架构转换为 implicit many-to-many relations,这将使 create
/connect
语法更容易。
我是后端和东西的新手。 我有两个模型:产品和城市。城市可以有很多产品,产品可以有很多城市,所以我创建了另一个 table ProductsOnCities:
model City {
id Int @id @default(autoincrement())
name String
pickupPoints PickupPoint[]
products ProductsOnCities[]
}
model Product {
id Int @id @default(autoincrement())
title String
price Int
cities ProductsOnCities[]
}
model ProductsOnCities {
city City @relation(fields: [cityId], references: [id])
cityId Int
product Product @relation(fields: [productId], references: [id])
productId Int
@@id([cityId, productId])
}
现在如何插入数据?例如,我想创建包含 4 个产品的城市(我的数据库中已经存在),我真的需要在那里创建 4 个对象,如 prisma docs 所示吗?以下是文档中的示例。
const assignCategories = await prisma.post.create({
data: {
title: 'How to be Bob',
categories: {
create: [
{
assignedBy: 'Bob',
assignedAt: new Date(),
category: {
connect: {
id: 9,
},
},
},
{
assignedBy: 'Bob',
assignedAt: new Date(),
category: {
connect: {
id: 22,
},
},
},
],
},
},
})
我就是这么做的:
const assignCategories = await prisma.city.create({
data: {
name: 'Toronto',
products: {
create: [
{
product: {
connect: {
id: 1
},
},
},
{
product: {
connect: {
id: 15
},
},
},
{
product: {
connect: {
id: 11
},
},
},
{
product: {
connect: {
id: 18
},
},
},
],
},
},
})
它工作得很好,但是有什么方法可以更简洁地做到这一点吗?我真的需要为我添加的每个产品传递一个新的“大”对象吗?我尝试将产品 ID 数组传递给连接,但它不起作用。
是的,您在使用 explicit many-to-many relations 时需要以这种方式传递它。
您可以将架构转换为 implicit many-to-many relations,这将使 create
/connect
语法更容易。