-
Hi. My schema: model User {
id Int @id @default(autoincrement())
templates Template[]
}
model Template {
id Int @id @default(autoincrement())
ownerId Int
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
} Next, I create an API to delete templates for the transmitted ID. However, it is important that each authorized user can only delete their own templates. Usually I would generate the following query: DELETE FROM "Template" WHERE id = <input.id> and "ownerId" = <context.user.id> However, the prisma does not allow me to generate such a query, throwing type error: db.template.delete({
where: {
id: input.id,
ownerId: ctx.user.id, // Type '{ id: number; ownerId: number; }' is not assignable to type 'TemplateWhereUniqueInput'. Object literal may only specify known properties, and 'ownerId' does not exist in type 'TemplateWhereUniqueInput'.
}
}) // .prisma/client/index.d.ts
export type TemplateWhereUniqueInput = {
id?: number
} I found a way to do what I want by deleting the templates as requested by the user update: db.user.update({
where: {
id: ctx.user.id
},
data: {
templates: {
delete: {
id: input.id
}
}
}
}) However, it is difficult to read and also makes the code verbose. Is there a way to make the same easier? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey @cawa-93 👋, Try adding a unique index to model User {
id Int @id @default(autoincrement())
templates Template[]
}
model Template {
id Int @id @default(autoincrement())
ownerId Int
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
@@unique([id, ownerId])
} Then you can update like so: await prisma.template.update({
where: {
id_ownerId: {
id: input.id,
ownerId: ctx.user.id
}
},
data: {...}
}) |
Beta Was this translation helpful? Give feedback.
-
any help? I dont think owerId a unique field。 Have other advice today? |
Beta Was this translation helpful? Give feedback.
Does this help?
https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#enable-the-ability-to-filter-on-non-unique-fields-with-userwhereuniqueinput
#15837