GORM Save 方法获取主键 ID 的教程
在 GORM 中,使用 Save 方法保存数据后,可以通过调用返回的 error 对象的方法来获取插入数据的主键 ID。
示例代码如下:
package main
import (
"fmt"
"log"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string
Email string
CreatedAt time.Time
UpdatedAt time.Time
}
func main() {
dsn := "root:password@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
user := User{Name: "John", Email: "john@example.com"}
err = db.Debug().Create(&user).Error
if err != nil {
log.Fatal(err)
}
fmt.Println("User ID:", user.ID)
}
在上述示例中,我们使用 gorm 的 Create 方法将数据保存到数据库中,并通过调用 user.ID 来获取插入数据的主键 ID。
原文地址: https://www.cveoy.top/t/topic/pd4P 著作权归作者所有。请勿转载和采集!