Grayson
Grayson

Reputation: 121

GORM 2.0 get last insert ID

I'm operating on a MySQL database using GORM v 2.0. I'm inserting row into database using GORM transaction (tx := db.Begin()). In previous GORM versions, Begin() returned sql.Tx object that allowed to use LastInsertId() method on query return parameter.

To do that in GORM v 2.0, i can simply call db.Last() function after insert row into database, or i can use smarter method?

Thank you.

Upvotes: 5

Views: 11374

Answers (1)

Christian
Christian

Reputation: 1808

In V2.0 the GetLastInsertId method was removed. As @rustyx says, the ID is populated in the model you pass the Create function. I wouldn't bother calling db.Last(&...) as this is a bit of a waste when the model will already have it.

    type User struct {
        gorm.Model
        Name string
    }

    user1 := User{Name: "User One"}

    _ = db.Transaction(func(tx *gorm.DB) error {
        tx.Create(&user1)
        return nil
    })

    // This is unnecessary
    // db.Last(&user1)

    fmt.Printf("User one ID: %d\n", user1.ID)

Upvotes: 7

Related Questions