How to Retrieve the Last Inserted ID in GORM 2.0?

Barbara Streisand
Release: 2024-10-25 11:55:02
Original
995 people have browsed it

How to Retrieve the Last Inserted ID in GORM 2.0?

Last Insert ID in GORM 2.0

In GORM 2.0, obtaining the last inserted ID after executing a database insertion has undergone changes compared to previous versions. This article explores how to retrieve the last inserted ID using the current version of GORM.

In GORM v2.0, the Begin() function does not return a sql.Tx object anymore, which previously provided the LastInsertId() method. Instead, the Last() function should be used after inserting a row into the database. Alternatively, a more efficient approach is available.

After a successful database insertion using the Create function, GORM automatically populates the ID in the model passed to the function. Therefore, calling db.Last(&model) is unnecessary as the model already contains the last inserted ID. This technique not only avoids unnecessary database calls but also ensures data integrity.

To demonstrate this, consider the following example:

<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
})

// This is unnecessary
// db.Last(&user1)

fmt.Printf("User one ID: %d\n", user1.ID)</code>
Copy after login

In this example, the user1 model automatically contains the last inserted ID after executing the Create function, which can be accessed directly using user1.ID. This method is efficient and eliminates the need for additional database queries or unnecessary function calls.

The above is the detailed content of How to 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!