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

Patricia Arquette
Release: 2024-10-31 12:48:01
Original
936 people have browsed it

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

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!

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!