How can I retrieve instance of last added item
Asked Answered
L

2

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?

Lamina answered 27/2, 2015 at 20:45 Comment(0)
P
18
type User struct {
  Id int
  Name string
}

user := User{Name: "jinzhu"}
db.Save(&user)
// user.Id is set to last insert id
Pitt answered 28/2, 2015 at 1:12 Comment(1)
I wasn't passing it as a pointer! It works well now. Meanwhile, thank you for a very useful library.Lamina
G
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
Genitourinary answered 16/10, 2018 at 7:27 Comment(2)
Can't we do this via db.Create?Litigable
@BalajiSrinivasan you can but Create insert the value into database and Save update value in database, if the value doesn't have primary key, will insert itGenitourinary

© 2022 - 2024 — McMap. All rights reserved.