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

DDD
Release: 2024-10-26 19:53:02
Original
161 people have browsed it

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>
Copy after login

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>
    Copy after login
  2. Use the Save function to insert the entity into the database:

    <code class="go">db.Save(&user)</code>
    Copy after login
  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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!