"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-10
Browse:940

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:

type User struct {
  Id int
  Name string
}

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3