Home  >  Article  >  Backend Development  >  How to Retrieve the Last Insert ID in GORM 2.0?

How to Retrieve the Last Insert ID in GORM 2.0?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:24:28359browse

How to Retrieve the Last Insert ID in GORM 2.0?

How to Retrieve Last Insert ID in GORM 2.0

In earlier GORM versions, the Begin() method returned a sql.Tx object that enabled the retrieval of the last insert ID using the LastInsertId() method. However, in GORM 2.0, this method has been removed.

Retrieving Last Insert ID in GORM 2.0

There are two methods to obtain the last insert ID in GORM 2.0:

1. Using db.Last():

After inserting a row into the database, you can invoke the db.Last() function. This will populate the model with the newly assigned ID:

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

2. Directly Accessing the Model's ID:

Alternatively, you can directly access the ID field of the model after insertion. The ID will have been automatically populated during the insert operation:

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

Recommendation:

It is recommended to use the second approach (directly accessing the model's ID) as it eliminates the need for an additional db.Last() call. This can improve performance, especially for high-volume insert operations.

The above is the detailed content of How to Retrieve the Last Insert ID in GORM 2.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