[英]How can I use createMany with foreign keys in prisma?
I am a beginner in using Prisma and am stuck at trying to figure out how to initially load data into postgres tables.我是使用 Prisma 的初学者,并且一直试图弄清楚如何最初将数据加载到 postgres 表中。 I have tried seeding my db as per this example in prisma https://github.com/prisma/prisma-examples/tree/latest/javascript/graphql-auth but it seems the main() is not getting triggered by the command "npx prisma db seed --preview-feature".
我已经尝试按照这个示例在 prisma https://github.com/prisma/prisma-examples/tree/latest/javascript/graphql-auth中播种我的数据库,但似乎 main() 没有被命令“触发” npx prisma db 种子 --preview-feature"。 So I tried to insert into my db through a temporary function but I am getting an invalid invocation error on starting dev server:
因此,我尝试通过临时 function 插入我的数据库,但在启动开发服务器时出现无效调用错误:
Foreign key constraint failed on the field: Animals_categoryName_fkey (index)
But I am not getting this error when I don't use foreign keys.但是当我不使用外键时,我没有收到此错误。 Below is my schema.prisma, types and the data that I need to add.
下面是我的 schema.prisma、类型和我需要添加的数据。
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]
}
`;
Part of data to add:要添加的部分数据:
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()})
If it helps in any way, I am using prisma 2.24, apollo and graphql with a postgres database.如果它有任何帮助,我将使用 prisma 2.24、apollo 和 graphql 和 postgres 数据库。 Any help or suggestion is greatly appreciated.
非常感谢任何帮助或建议。
Prisma will not let you create a Animal
record with a certain foreign key provided in Animals.categoryName
if there is no matching record with the same categoryName
in the Category
table.如果
Category
表中没有具有相同categoryName
的匹配记录,Prisma 将不允许您使用Animals.categoryName
中提供的某个外键创建Animal
记录。 This is called a Foreign key constraint.这称为外键约束。
To satisfy the Foreign key constraint you need to make sure a record already exists in the Category
table with the same categoryName
as the record you're trying to create in the Animals
table.要满足外键约束,您需要确保
Category
表中已经存在与您尝试在Animals
表中创建的记录具有相同categoryName
的记录。 For the example you mentioned, this would mean creating two records in the Category
table having Category.categoryName
of "mammals" and "cats".对于您提到的示例,这意味着在
Category.categoryName
的“mammals”和“cats”的Category
表中创建两条记录。
Before running the animals.createMany
query, you can do something like this,在运行
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
It's not possible to create both Animal
and Category
wih a single createMany
query because you cannot access relations in a CreateMany query .无法使用单个
createMany
查询同时创建Animal
和Category
,因为您无法访问 CreateMany 查询中的关系。 If this is something you want to do, consider using create
instead of createMany
.如果这是您想要做的事情,请考虑使用
create
而不是createMany
。 You can find more information about this in the nested writes section of the Prisma docs.您可以在 Prisma 文档的嵌套写入部分中找到有关此的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.