Home  >  Article  >  Backend Development  >  How do I Retrieve the Last Inserted ID in GORM 2.0?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 09:26:28964browse

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>

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!

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