Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve instance of last added item

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?

like image 657
sathishvj Avatar asked Feb 27 '15 20:02

sathishvj


2 Answers

type User struct {
  Id int
  Name string
}

user := User{Name: "jinzhu"}
db.Save(&user)
// user.Id is set to last insert id
like image 164
Jinzhu Avatar answered Sep 18 '22 16:09

Jinzhu


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
like image 43
Nisal Edu Avatar answered Sep 20 '22 16:09

Nisal Edu