如何在 prisma 中将 createMany 与外键一起使用?

How can I use createMany with foreign keys in prisma?

我是使用 Prisma 的初学者,一直在尝试弄清楚如何最初将数据加载到 postgres 表中。我已经尝试按照这个例子在 prisma 中播种我的数据库 https://github.com/prisma/prisma-examples/tree/latest/javascript/graphql-auth 但似乎 main() 没有被命令“npx prisma 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
}

类型定义--

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",
                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: "gorilla",
                categoryName: "mammals"
            }            
        ]
    })
}

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

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

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

要满足外键约束,您需要确保 Category table 中已存在与您尝试在其中创建的记录相同的 categoryName 记录Animals table。对于您提到的示例,这意味着在 Category table 中创建两条记录,其中 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 

无法通过单个 createMany 查询同时创建 AnimalCategory,因为您是 Prisma 文档的 cannot access relations in a CreateMany query. If this is something you want to do, consider using create instead of createMany. You can find more information about this in the nested writes 部分。