Be able to update or retrieve a single record including non-unique fields in the "where" conditions.
See original GitHub issueProblem
I am unable to utilize non-unique fields in single update queries. To be clear, I want to still use the unique fields, I just want to filter it down even more.
Suggested solution
Here are my models
model Person {
id String @id @db.Uuid
client Client[]
}
model Client {
id String @id @db.Uuid
name String
personId String @db.Uuid
person Person @relation(fields: [personId], references: [id])
}
I have “people” who have “clients” attached to them. Only the person who owns the client can update the name. So when an API call comes in, I know who the current person is and what client they’re trying to update. So the update query I would like to use is this:
const client = await prisma.client.update({
data: { name: input.name },
where: {
id: input.clientId,
personId: input.personId
}
})
but it only allows fields which are marked as @unique
or @id
Alternatives
One alternative is to do a .findUnique({ where: { id: input.clientId } })
and then check if the personId of the client is the same as the one passed in. This however creates two database calls where only one is needed.
Another alternative is to do a .updateMany({ where: { id: input.clientId, personId: input.personId } })
but I don’t get any of the clients back. If I got the clients back in the query and if there was a limit
I could pass in to limit it to one, I would feel better about this so it wouldn’t have to do any unneeded scans of the rows, but it still feels less idiomatic than updating the .update()
command to allow for non-unique fields.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:55
- Comments:49 (5 by maintainers)
Top GitHub Comments
@janpio I use the additional filter as a way of further qualifying the operation.
For example, an API request comes in to update a Todo item. I have the unique id of the todo from the parsed URL, and I have the current user from the auth token. I want to send a single update command to the database where the id is the given todo id and the owner of the todo is the current user’s id. This way, if someone tries to update a todo item they are not owner of, the update returns null.
I guess that would work, it just seems superfluous to add a unique index that includes a field that is already considered unique, especially if it’s a workaround for a missing feature. Adding indexes to a database isn’t “free” in that adding an indexes increases disk usage. It’s probably not significant enough for my current use case currently, but I could see a future use case where adding unique indexes to every combination of fields I need to conditionally update/delete would be prohibitive.