Retrieving the Instance of the Last Added Item in GORM with MySQL Backend
When working with database operations using GORM and a MySQL backend, you may encounter situations where you need to retrieve the instance of the row that was most recently added during a Create operation. This is similar to the well-known concept of last-insert-id in SQL databases, which provides the ID of the last row inserted.
Solution:
To retrieve the instance of the last added item in GORM, you can utilize the following approach:
<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>
In this example, we have defined a User struct that represents the data we want to insert. When the db.Save method is called with the address of the user struct, GORM automatically executes an INSERT query and retrieves the Id field from the database, which is the primary key assigned by MySQL.
By accessing user.Id after the db.Save operation, you will have the ID of the newly inserted row, allowing you to retrieve or further manipulate the object as needed.
The above is the detailed content of How to Retrieve the Instance of the Last Added Item in GORM with a MySQL Backend?. For more information, please follow other related articles on the PHP Chinese website!