Home  >  Article  >  Backend Development  >  How to Retrieve the Last Insert ID or Entity with GORM and MySQL?

How to Retrieve the Last Insert ID or Entity with GORM and MySQL?

DDD
DDDOriginal
2024-10-26 19:53:02166browse

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:

  1. Create a new instance of the entity:

    <code class="go">user := User{Name: "jinzhu"}</code>
  2. Use the Save function to insert the entity into the database:

    <code class="go">db.Save(&user)</code>
  3. After the Save operation, the Id field of the user instance will contain the last inserted ID.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn