Aayush Taneja
Aayush Taneja

Reputation: 561

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.

Upvotes: 7

Views: 10916

Answers (3)

xdzc
xdzc

Reputation: 1471

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

Upvotes: 16

dave
dave

Reputation: 64657

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)
}

Upvotes: 1

Jessie
Jessie

Reputation: 2475

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.

Upvotes: -3

Related Questions