P
Prisma22h ago
Mike

How can I perform batch updates unique entities in Prisma?

How can I perform batch updates in Prisma — akin to createMany — by passing an array or collection to a single operation? I’m working inside long-lived interactive transactions and need to update multiple records by their unique IDs. What’s the best approach? 1. Using Promise.all([ tx.model.update(…)*N ]) for each item 2. Writing a custom extension or helper with an SQL builder 3. Executing raw SQL via tx.$executeRaw Could you also show an example SQL query that accomplishes this? (I’m not very familiar with SQL, so any guidance is appreciated.)
WITH updates (id, new_name, new_status) AS (
VALUES
(1, 'Alice', 'active'),
(2, 'Bob', 'pending'),
(5, 'Charlie', 'banned')
)
UPDATE users u
SET
name = updates.new_name,
status = updates.new_status
FROM updates
WHERE u.id = updates.id;
WITH updates (id, new_name, new_status) AS (
VALUES
(1, 'Alice', 'active'),
(2, 'Bob', 'pending'),
(5, 'Charlie', 'banned')
)
UPDATE users u
SET
name = updates.new_name,
status = updates.new_status
FROM updates
WHERE u.id = updates.id;
3 Replies
Prisma AI Help
Prisma AI Help22h ago
You chose to debug with a human. They'll tinker with your query soon. If you get curious meanwhile, hop into #ask-ai for a quick spin!
Nurul
Nurul15h ago
Hey! It seems that you are looking for functionality mentioned in this feature request: https://github.com/prisma/prisma/issues/6862 The most straight forward approach would be using transactions with multiple update operations:
await prisma.$transaction(async (tx) => {
await tx.users.update({ where: { id: 1 }, data: { name: 'Alice', status: 'active' } });
await tx.users.update({ where: { id: 2 }, data: { name: 'Bob', status: 'pending' } });
await tx.users.update({ where: { id: 5 }, data: { name: 'Charlie', status: 'banned' } });
});
await prisma.$transaction(async (tx) => {
await tx.users.update({ where: { id: 1 }, data: { name: 'Alice', status: 'active' } });
await tx.users.update({ where: { id: 2 }, data: { name: 'Bob', status: 'pending' } });
await tx.users.update({ where: { id: 5 }, data: { name: 'Charlie', status: 'banned' } });
});
GitHub
Update multiple records with different values · Issue #6862 · pri...
Problem Lets consider a user table with columns ID and NAME . If i wish to update multiple Names based on their IDs, for example - For id=1, name should be updated to name="abc" For id=2,...
Mike
MikeOP15h ago
@Nurul (Prisma) Thank you! I found several related issues there. I’ll try some of those over the next few days. Is there a plan to implement this feature? This topic was probably raised about five years ago, and there’s still no solution from Prisma. 😦 @Nurul (Prisma) Inside transaction better way is?
await Promise.all(items.map(item => tx.model.update({where: {id: item.id}, data: item.data }))
await Promise.all(items.map(item => tx.model.update({where: {id: item.id}, data: item.data }))

Did you find this page helpful?