Why did the foreign key constraint fail on the column: postId? How can I fill the prisma studio with the same postId values?
Faker create table git example
images: {
create: [
{
imagePuth: faker.image.image(),
postId: faker.datatype.number({ min: 1, max: 7 }),
},
],
},
Environment variables loaded from .env
Running seed command `ts-node prisma/seed.ts` ...
Start seeding ...
PrismaClientKnownRequestError:
Invalid `prisma.user.create()` invocation in
Z:\spa\project\server\prisma\seed.ts:18:36
15 async function main() {
16 console.log(`Start seeding ...`);
17 for (let i = 0; i < 7; i++) {
ā 18 const user = await prisma.user.create(
Foreign key constraint failed on the field: `postId`
at cb (Z:\spa\project\server\node_modules\@prisma\client\runtime\index.js:38537:17)
at async main (Z:\spa\project\server\prisma\seed.ts:18:18) {
code: 'P2003',`enter code here`
clientVersion: '3.3.0',
meta: { field_name: 'postId' }
}
An error occured while running the seed command:
Error: Command failed with exit code 1: ts-node prisma/seed.ts
images: {
create: [
{
imagePuth: faker.image.image(),
postId: 1,
},
],
},
console.log('postId ' + faker.datatype.number({ min: 1, max: 7 }));
console.log(`Created user with id: ${user.id}`);
Running seed command `ts-node prisma/seed.ts` ...
Start seeding ...
postId 7
Created user with id: 1
postId 3`enter code here`
Created user with id: 2
postId 5
Created user with id: 3
postId 7
Created user with id: 4
postId 5
Created user with id: 5
postId 5
Created user with id: 6
postId 7
Created user with id: 7
Seeding finished.
The seed command has been executed.
images: {
create: [
{
imagePuth: faker.image.image(),
postId: 2,
},
],
},
Thank you I did so
Tasin Ishmam
import { PrismaClient, Prisma } from '@prisma/client';
//import faker from 'faker';
const prisma = new PrismaClient();
const faker = require('faker');
async function main() {
console.log(`Start seeding ...`);
for (let i = 0; i < 7; i++) {
const user = await prisma.user.create({
data: {
email: faker.internet.email(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
avatar: faker.image.avatar(),
},
});
console.log({ user });
}
for (let i = 0; i < 7; i++) {
const post = await prisma.post.create({
data: {
title: faker.name.title(),
content: faker.lorem.paragraphs(),
userId: faker.datatype.number({ min: 1, max: 7 }),
},
});
console.log({ post });
}
for (let i = 0; i < 14; i++) {
const image = await prisma.image.create({
data: {
imagePuth: faker.image.image(),
postId: faker.datatype.number({ min: 1, max: 7 }),
userId: faker.datatype.number({ min: 1, max: 7 }),
},
});
console.log({ image });
}
console.log(`Seeding finished.`);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});