How can I retrieve instance of last added item

sathishvj picture sathishvj · Feb 27, 2015 · Viewed 10.8k times · Source

I'm using github.com/jinzhu/gorm with a mysql backend. I want to retrieve the Id (or the full entity) of the row in the previous Create call.

As in, last-insert-id: (http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id)

How can I do this?

Answer

Jinzhu picture Jinzhu · Feb 28, 2015
type User struct {
  Id int
  Name string
}

user := User{Name: "jinzhu"}
db.Save(&user)
// user.Id is set to last insert id