如何在prisma中使用带有外键的createMany?

问题描述

我是使用 prisma 的初学者,并且一直试图弄清楚如何最初将数据加载到 postgres 表中。我已经尝试按照这个例子在prisma中播种我的数据库 https://github.com/prisma/prisma-examples/tree/latest/javascript/graphql-auth 但似乎 main() 没有被命令“npxprisma db seed --preview-feature”触发。 所以我试图通过一个临时函数插入到我的数据库中,但我在启动开发服务器时收到无效调用错误

Foreign key constraint Failed on the field: Animals_categoryName_fkey (index)

但是当我不使用外键时我没有收到这个错误。下面是我的 schema.prisma、类型和我需要添加的数据。

Schema.prisma

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Animals{
  id Int @id @default(autoincrement())
  image String
  price String
  description String[]
  stock Int
  onSale Boolean
  title String
  category Category @relation(fields: [categoryName],references: [categoryName])
  slug String @unique
  categoryName String
}

model Category{
  id Int @id @default(autoincrement())
  image String
  categoryName String @unique
  animals Animals[]
}

model MainCards{
  cardId Int @id @default(autoincrement())
  image String
  title String
}

typedefs--

const typeDefs = gql`
      type MainCard {
          title: String!
          image: String!
      }
    
      type Animals{
        id: ID!
        image: String!
        price: String!
        description: [String!]!
        stock: Int!
        onSale: Boolean
        slug: String
        categoryName: String
        title: String
      }
    
      type Category{
        id: ID!
        image: String!
        categoryName: String!
      }
    
      type Query {
        mainCards: [MainCard]
        animals: [Animals]
        animal(slug: String!): Animals
        categories: [Category]
        category(categoryName: String!): [Animals]
      }
    `;

添加的部分数据:

const AnimalsData = async () => {
    await prisma.animals.createMany({
        data: [
            {
                image: "lion",title: "7-year Male Lion with Large Well Kept Main with a Beautiful Yellow/brownish Color",price: "23,322",description: [
                    "Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.","Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.","Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.","Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum."
                ],stock: 14,onSale: false,slug: "lion",categoryName: "cats"
            },{
                image: "gorilla",title: "Black Haired Gorilla with broad Chest and Shoulder. Would be an Excellent Spot at the Gym",price: "47,775",slug: "gorilla",categoryName: "mammals"
            }            
        ]
    })
}

AnimalsData()
.catch(e => {throw e})
.finally(async () => {await prisma.$disconnect()})

如果有任何帮助,我将使用带有 postgres 数据库prisma 2.24、apollo 和 graphql。 非常感谢任何帮助或建议。

解决方法

如果 Animal 表中没有具有相同 Animals.categoryName 的匹配记录,Prisma 将不允许您使用 categoryName 中提供的特定外键创建 Category 记录.这称为外键约束。

要满足外键约束,您需要确保 Category 表中已存在与您尝试在 categoryName 中创建的记录具有相同 Animals 的记录桌子。对于您提到的示例,这意味着在 Category 表中创建两个记录,其中 Category.categoryName 为“哺乳动物”和“猫”。

在运行 animals.createMany 查询之前,您可以执行以下操作,

await prisma.category.createMany({
        data: [
            {
                categoryName: "mammals",image: "__PLACEHOLDER_VALUE__"  // change appropriately
            },{
                categoryName: "cats",image: "__PLACEHOLDER_VALUE__"  // change appropriately
            }
        ]
    })

//  ...run await prisma.animals.createMany 

不可能使用单个 Animal 查询同时创建 CategorycreateMany,因为您 cannot access relations in a CreateMany query。如果这是您想要做的事情,请考虑使用 create 而不是 createMany。您可以在 Prisma 文档的 nested writes 部分找到更多相关信息。