Retrieving the Id of Last Added Item Using GORM
When working with a MySQL backend in GORM, retrieving the id of the last added item can be useful for various scenarios. This article explains how to accomplish this task effectively.
GORM exposes a straightforward mechanism to retrieve the last-inserted id. To illustrate, consider the following example:
<code class="go">type User struct { Id int Name string } user := User{Name: "jinzhu"} db.Save(&user) // user.Id is set to last insert id</code>
After performing the Save operation, the Id field of the user instance will automatically be populated with the id of the last inserted row. This is enabled by GORM's integration with the underlying database, which handles the last-insert-id functionality transparently.
By utilizing this feature, developers can easily access the id of the newly created record without additional queries or complex coding. This can simplify development and reduce the need for manual id retrieval logic.
The above is the detailed content of How to Retrieve the ID of the Last Added Item Using GORM?. For more information, please follow other related articles on the PHP Chinese website!