How to Get the Instance or ID of the Last Added Item in GORM?

Susan Sarandon
Release: 2024-10-30 21:17:03
Original
573 people have browsed it

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:

  1. Define a struct representing your database table, ensuring it includes a primary key field (typically an integer named "Id").
  2. Create an instance of this struct and populate its non-primary key fields.
  3. Use the "Save" method of GORM to insert the new row into the database.
  4. After the "Save" operation, the "Id" field of your struct will be automatically populated with the ID of the last inserted row.

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

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!

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
Latest Articles by Author
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!