How do I Retrieve the Last Inserted ID in GORM 2.0?

Linda Hamilton
Release: 2024-10-25 09:26:28
Original
984 people have browsed it

How do I Retrieve the Last Inserted ID in GORM 2.0?

Querying Last Insert ID in GORM 2.0

Unlike previous versions of GORM, GORM 2.0 no longer provides the LastInsertId() method to retrieve the last inserted ID. Instead, it populates the ID field directly into the model passed to the Create() function.

For instance, consider the following code:

<code class="go">type User struct {
    gorm.Model
    Name string
}

user1 := User{Name: "User One"}

_ = db.Transaction(func(tx *gorm.DB) error {
    tx.Create(&user1)
    return nil
})</code>
Copy after login

After executing this code, the ID field of user1 will be populated with the last inserted ID. There is no need to call db.Last() to retrieve it.

This revised approach simplifies the process of obtaining the last insert ID while also eliminating the potential performance overhead of additional database queries.

The above is the detailed content of How do I Retrieve the Last Inserted ID in GORM 2.0?. 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!