Home > Article > Backend Development > How to Get the Instance or ID of the Last Added Item in GORM?
Retrieving the Instance of Last Added Item in GORM
When working with a MySQL backend in Go using the GORM library, there are situations where you may need to obtain the instance or ID of the last row inserted during a Create operation. This can be useful for tracking the most recently added item and performing subsequent actions based on its properties.
SOLUTION
GORM simplifies the process of retrieving the last inserted ID. By default, GORM sets the primary key of the newly created object with the value from the last insert operation. Therefore, you can access the ID or the entire object directly using the following steps:
EXAMPLE
Consider the following GORM model and code snippet:
<code class="go">type User struct { Id int Name string } user := User{Name: "jinzhu"} db.Save(&user) fmt.Println(user.Id) // Prints the last inserted ID</code>
In this example, the "Save" method inserts the "User" instance into the database and automatically sets the "Id" field with the value from the last insert operation. You can then access the "Id" property to obtain the primary key of the newly created row.
The above is the detailed content of How to Get the Instance or ID of the Last Added Item in GORM?. For more information, please follow other related articles on the PHP Chinese website!