首页 > 解决方案 > Prisma 如何创建对数据模型的多个引用

问题描述

我在如何建立以下关系时遇到问题:

店铺 -< 产品 >- 类别

一家商店可以有很多产品。一个类别可以有许多产品。我的问题是在类别已经播种后尝试播种商店/产品。

model Store {
  id      String    @id @default(uuid())
  name    String    @unique
  Product Product[]
}

model Category {
  id      String    @id
  name    String    @unique
  Product Product[]
}

model Product {
  id               String      @default(uuid())
  name             String      @unique
  creator          Store @relation(fields: [store_id], references: [id])
  store_id   String // relation to  creator field
  product_category Category @relation(fields: [category_id], references: [id])
  category_id  String // relation to product_category field
  price        Number
}

我遇到的问题是如何播种?我尝试过类似下面的代码。我基本上在填充商店时使用该商店的名称并将其应用于地图。该映射会将完整的产品对象推送到数据库。该映射对象已经完成了类别的映射:

// get the category that i want to seed
 const consumerGoods = await prisma.category.findUnique({
    where: {
      id: 'CS',
    },
  })
  const productMap = {
    Sports: [
      {
        name: 'basketball',
        product_category: consumerGoods, // store category in storemap
        price: 35.95
     }
    ],
    Games: [
      {
        name: 'ps5',
        product_category: consumerGoods,
        price: 399.99
      }
    ],
    Toys: [
      {
        name: 'Super Man',
        product_category: consumerGoods,
        price: 14.50
      }
    ]
  }

 for (const name of storeNames) {
    institutions.push(await prisma.store.upsert({
      where: { name},
      update: {},
      create: {
        name: name,
        Product: {
          create:  productMap[name]  // place complete object in create
        },
      },
    }))
  }

当我这样做时,它会抱怨:

 Unknown arg `id` in create.Product.create.0.product_category.id

我如何克服这个错误?

标签: typescriptnestjsprismaprisma2

解决方案


推荐阅读