how to delete post if it has likes

Hello lets say I have a post that i want the user to be able to delete, however the post also can have likes. If I use something like this:
delete: protectedProcedure
.input(z.object({
postId: z.string(),
}))
.mutation(async ({ctx, input}) => {
await ctx.prisma.post.delete({
where: {
id: input.postId,
}
})
}),
});
delete: protectedProcedure
.input(z.object({
postId: z.string(),
}))
.mutation(async ({ctx, input}) => {
await ctx.prisma.post.delete({
where: {
id: input.postId,
}
})
}),
});
prisma yells at me The change you are trying to make would violate the required relation 'LikeToPost' between the Like and Post models. How to solve that?
6 Replies
jack
jack2y ago
pretty sure you either give some sort of cascade instruction, or just delete all the associated likes first, and then delete the post i forget how/if cascade works in prisma
noctate
noctateOP2y ago
oh just reading prisma docs it seems like i need to do something like this
const deletePosts = prisma.post.deleteMany({
where: {
authorId: 7,
},
})

const deleteUser = prisma.user.delete({
where: {
id: 7,
},
})

const transaction = await prisma.$transaction([deletePosts, deleteUser])
const deletePosts = prisma.post.deleteMany({
where: {
authorId: 7,
},
})

const deleteUser = prisma.user.delete({
where: {
id: 7,
},
})

const transaction = await prisma.$transaction([deletePosts, deleteUser])
andersgee
andersgee2y ago
you can set ondelete cascade in your schema unfortunately this is not allowed on some db providers such as planetscale
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Yoers
Yoers2y ago
I think it is allowed on planetscale, cascade's are just handled within the prisma client if you set relationMode to prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
// Use this
relationMode = "prisma"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
// Use this
relationMode = "prisma"
}
https://www.prisma.io/docs/concepts/components/prisma-schema/relations/relation-mode#how-to-set-the-relation-mode-in-your-prisma-schema This chart shows you what is emulated https://www.prisma.io/docs/concepts/components/prisma-schema/relations/relation-mode#which-referential-actions-are-emulated
andersgee
andersgee2y ago
sorry, "not allowed" was the wrong word choice, a better wording it that its faked ("emulated by prisma client")
There are performance implications to emulation of referential integrity and referential actions in the Prisma Client. In cases where the underlying database supports foreign keys, it is usually the preferred choice.
There are performance implications to emulation of referential integrity and referential actions in the Prisma Client. In cases where the underlying database supports foreign keys, it is usually the preferred choice.
Want results from more Discord servers?
Add your server