How to retrieve the last insert ID in GORM v2.0?

DDD
Release: 2024-10-30 06:24:03
Original
150 people have browsed it

How to retrieve the last insert ID in GORM v2.0?

GORM 2.0: Retrieving Last Insert ID

When using GORM v2.0 to insert data into a MySQL database, the LastInsertId() method is no longer available through the Begin() method. Instead, there are two options for retrieving the last insert ID:

Option 1: Use the db.Last() Function

After inserting a row into the database, call the db.Last() function and pass it a pointer to the model. The model will be populated with the inserted values, including the last insert ID.

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

db.Last(&user1)

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

Option 2: Access the ID Directly

The ID is also populated in the model that you pass to the Create function. You can access it directly without using db.Last().

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

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

The above is the detailed content of How to retrieve the last insert ID in GORM v2.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
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!