Querying Last Insert ID in GORM 2.0
Unlike previous versions of GORM, GORM 2.0 no longer provides the LastInsertId() method to retrieve the last inserted ID. Instead, it populates the ID field directly into the model passed to the Create() function.
For instance, consider the following code:
type User struct {
gorm.Model
Name string
}
user1 := User{Name: "User One"}
_ = db.Transaction(func(tx *gorm.DB) error {
tx.Create(&user1)
return nil
})
After executing this code, the ID field of user1 will be populated with the last inserted ID. There is no need to call db.Last() to retrieve it.
This revised approach simplifies the process of obtaining the last insert ID while also eliminating the potential performance overhead of additional database queries.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3