7

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
sathishvj
  • 1,394
  • 2
  • 17
  • 28

2 Answers2

18
type User struct {
  Id int
  Name string
}

user := User{Name: "jinzhu"}
db.Save(&user)
// user.Id is set to last insert id
Community
  • 1
  • 1
Jinzhu
  • 485
  • 4
  • 8
3

Try as follows

type User struct {
  Id   int    `gorm:"column:id; PRIMARY_KEY" json:"id"`
  Name string `gorm:"column:name" json:"name"`
}

user := User{Name: "Andy"}
db.Save(&user)
// user.Id is set to last insert id
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34