Let's assume, I have the following schema,
type Users struct {
ID int gorm:"column:id;primaryKey;"
Name string gorm:"column:"name;"
IsActive bool gorm:"column:is_active;"
Remarks string gorm:"column:"remarks;"
}
I have the ids (primary key), is_active and remarks with me. Now I wanted to update these values for different ids in bulk.
I was able to see a thread related to this in, but it is not associated with gorm. Updating multiple rows with different primary key in one query in PostgreSQL?
What I'm trying to achieve is to do the following:
Instead of updating one by one,
UPDATE users SET is_active = true, remarks = 'activated_by_cron' where id = 1;
UPDATE users SET is_active = false, remarks = 'deactivated_by_cron' where id = 2;
UPDATE users SET is_active = true, remarks = 'activated_by_user' where id = 3;
`
Update everything in a single query,
update users as u set
is_active = c.is_active,
remarks = c.remarks
from (values
(1, true, 'activated_by_cron'),
(2, false, 'deactivated_by_cron'),
(3, true, 'activated_by_user')
) as c(id, is_active, remarks)
where c.id = u.id
My temporary solution was to write a custom utility function to create a raw query as explained above and then pass it to gorm to execute. But I feel this can be implemented in a better way.
Have someone faced this challenge before? If yes, how did you solve it?