Home >Backend Development >Golang >How to Retrieve the Last Insert ID or Entity with GORM and MySQL?
Retrieving the Last Insert ID or Entity with GORM and MySQL
When using GORM with a MySQL backend, it's often desirable to retrieve the ID or the entire entity of the last row created during a Create operation. This is commonly known as the "last-insert-id" in MySQL.
To accomplish this, GORM provides a simple and straightforward mechanism. After inserting a new entity, the Id field of the entity will be automatically assigned with the last inserted ID.
For instance, consider the following GORM model:
<code class="go">type User struct { Id int Name string }</code>
To retrieve the last inserted ID, follow these steps:
Create a new instance of the entity:
<code class="go">user := User{Name: "jinzhu"}</code>
Use the Save function to insert the entity into the database:
<code class="go">db.Save(&user)</code>
You can also retrieve the full entity along with the last inserted ID by following the same procedure. The Save function returns the newly created entity as an argument, allowing you to access its properties and relationships.
The above is the detailed content of How to Retrieve the Last Insert ID or Entity with GORM and MySQL?. For more information, please follow other related articles on the PHP Chinese website!