Home  >  Article  >  Backend Development  >  How to Retrieve the ID of a Recently Added Item in Go with Gorm and MySQL?

How to Retrieve the ID of a Recently Added Item in Go with Gorm and MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 12:48:01932browse

How to Retrieve the ID of a Recently Added Item in Go with Gorm and MySQL?

Retrieving Instance of Recently Added Item

When utilizing the gorm package with a MySQL backend, retrieving the ID or full entity of the last added item can prove challenging. Fortunately, there exists a solution inspired by the concept of last-insert-id in MySQL.

To accomplish this, consider the following code snippet:

<code class="go">type User struct {
  Id int
  Name string
}

user := User{Name: "jinzhu"}
db.Save(&user)
// user.Id is set to last insert id</code>

In this example, a User struct is created and subsequently saved to the database using the db.Save function. Afterward, the Id field of the user struct will be automatically set to reflect the last inserted ID.

This approach leverages gorm's ability to automatically set the primary key value of newly created structs. By storing the ID in the user.Id field, you can conveniently access the ID of the recently added item.

The above is the detailed content of How to Retrieve the ID of a Recently Added Item in Go 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