Home >Backend Development >Golang >How to Retrieve the Last Inserted ID in GORM 2.0?
Last Insert ID in GORM 2.0
In GORM 2.0, obtaining the last inserted ID after executing a database insertion has undergone changes compared to previous versions. This article explores how to retrieve the last inserted ID using the current version of GORM.
In GORM v2.0, the Begin() function does not return a sql.Tx object anymore, which previously provided the LastInsertId() method. Instead, the Last() function should be used after inserting a row into the database. Alternatively, a more efficient approach is available.
After a successful database insertion using the Create function, GORM automatically populates the ID in the model passed to the function. Therefore, calling db.Last(&model) is unnecessary as the model already contains the last inserted ID. This technique not only avoids unnecessary database calls but also ensures data integrity.
To demonstrate this, consider the following example:
<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 }) // This is unnecessary // db.Last(&user1) fmt.Printf("User one ID: %d\n", user1.ID)</code>
In this example, the user1 model automatically contains the last inserted ID after executing the Create function, which can be accessed directly using user1.ID. This method is efficient and eliminates the need for additional database queries or unnecessary function calls.
The above is the detailed content of How to Retrieve the Last Inserted ID in GORM 2.0?. For more information, please follow other related articles on the PHP Chinese website!