Home  >  Article  >  Backend Development  >  How to retrieve the last insert ID in GORM v2.0?

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

DDD
DDDOriginal
2024-10-30 06:24:03139browse

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>

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>

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!

Statement:
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