Home > Backend Development > Golang > How to Retrieve the ID of the Last Added Item Using GORM?

How to Retrieve the ID of the Last Added Item Using GORM?

Linda Hamilton
Release: 2024-10-28 20:52:31
Original
1010 people have browsed it

How to Retrieve the ID of the Last Added Item Using GORM?

Retrieving the Id of Last Added Item Using GORM

When working with a MySQL backend in GORM, retrieving the id of the last added item can be useful for various scenarios. This article explains how to accomplish this task effectively.

GORM exposes a straightforward mechanism to retrieve the last-inserted id. To illustrate, consider the following example:

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

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

After performing the Save operation, the Id field of the user instance will automatically be populated with the id of the last inserted row. This is enabled by GORM's integration with the underlying database, which handles the last-insert-id functionality transparently.

By utilizing this feature, developers can easily access the id of the newly created record without additional queries or complex coding. This can simplify development and reduce the need for manual id retrieval logic.

The above is the detailed content of How to Retrieve the ID of the Last Added Item Using 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