Home  >  Article  >  Backend Development  >  How to Get the Instance or ID of the Last Added Item in GORM?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-30 21:17:03574browse

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>

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!

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