I need help working through this error. I have a one-to many-self-relationship that dictates all the comments/children a post will have. see schema below.
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
description String
postedBy User? @relation(fields: [postedById], references: [id])
postedById Int?
votes Vote[]
comments Post[] @relation(name: "comment")
parent Post? @relation(name: "comment", fields: [parentId], references: [id])
parentId Int? @default(0)
}
As you can see, the parentId defaults to zero. I always want the root post to have a parentId of zero to signify that it is a root post because there is no Post with Id 0 for the foreign key to reference.
When I added the one-many-self-relationship with default 0 my prisma populated correctly, ignoring foreign-key errors in my db as seen below.
The parent field is null? or undefined? because the parentId = 0 doesn't exist. That is good because those are root posts. The problem is when I try and make a post mutation using gql I get a foreign key error because there is no post with id 0. See mutation below.
const { userId, prisma } = context;
if (userId === null) throw new Error("Not Authenticated");
const newPost = await prisma.post.create({
data: {
description: args.description,
postedBy: { connect: { id: userId } },
parent: { connect: { id: args.parentId } },
},
});
context.pubsub.publish("NEW_POST", newPost);
return newPost;
}
if I replace args.parentId = 0 I will get the foreign key error in gql, if args.parentId = 1 I will not get an error but the post is no longer considered a root post (bad).
can someone please offer me some guidance with this issue? I would like to ignore the foreign key error if possible.
I have looked into the referential actions (seen below) to set a default on post but I don't think my use case is the purpose of referential actions so I am not sure where to look...
model Post {
id Int @id @default(autoincrement())
title String
authorUsername String? @default("anonymous")
author User? @relation(fields: [authorUsername], references: [username], onUpdate: SetDefault)
}