'Gorm Update and Get the Updated Rows in a single operation?

Is there any way to get the rows that have been updated using the update command in Gorm, using a single operation.



Solution 1:[1]

It's not pretty, but since you are using postgres you can do:

realDB := db.DB()
rows, err := realDB.Query("UPDATE some_table SET name = 'a' WHERE name = 'b' RETUNING id, name") 
//you could probably do db.Raw but I'm not sure
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
    var id int
    var name string
    err := rows.Scan(&id, &name)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(id, name)
}

Solution 2:[2]

I know this is like a million years old but for the sake of completion here's the Gorm way of doing it - clauses.

    result := r.Gdb.Model(&User{}).Clauses(clause.Returning{}).Where("id = ?", "000-000-000").Updates(content)

Ref: Gorm Returning Data From Modified Rows

Solution 3:[3]

This is a decent solution if you know the number of rows you're updating is relatively small (<1000)

var ids []int
var results []YourModel

// Get the list of rows that will be affected
db.Where("YOUR CONDITION HERE").Table("your_table").Select("id").Find(&ids)
query := db.Where("id IN (?)", ids)

// Do the update
query.Model(&YourModel{}).Updates(YourModel{field: "value"})

// Get the updated rows
query.Find(&results)

This is safe against race conditions since it uses the list of IDs to do the update instead of repeating the WHERE clause. As you can imagine this becomes a bit less practical when you start talking about thousands of rows.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dave
Solution 2 cinfwatd
Solution 3 Jessie