GORM 2.0 获取最后插入 ID

GORM 2.0 get last insert ID

我正在使用 GORM v 2.0 在 MySQL 数据库上运行。我正在使用 GORM 事务 (tx := db.Begin()) 将行插入数据库。在以前的 GORM 版本中,Begin() returned sql.Tx 对象允许在查询 return 参数上使用 LastInsertId() 方法。

要在 GORM v 2.0 中做到这一点,我可以在将行插入数据库后简单地调用 db.Last() 函数,或者我可以使用更智能的方法?

谢谢。

在 V2.0 中删除了 GetLastInsertId 方法。正如@rustyx 所说,ID 填充在您传递 Create 函数的模型中。我不会打扰调用 db.Last(&...),因为当模型已经有了它时,这有点浪费。

    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)