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:
<code class="go">type User struct { gorm.Model Name string } user1 := User{Name: "User One"} _ = db.Transaction(func(tx *gorm.DB) error { tx.Create(&user1) return nil })</code>
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.
The above is the detailed content of How do I Retrieve the Last Inserted ID in GORM 2.0?. For more information, please follow other related articles on the PHP Chinese website!