1 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
您不必Save記錄您已經(jīng)傳遞的記錄Create。
您可以通過運(yùn)行以下命令對(duì)此進(jìn)行測(cè)試:
main.go
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Product{})
var product Product
if db.First(&product).Error == gorm.ErrRecordNotFound {
fmt.Println("no product record, creating now...")
db.Create(&Product{Code: "D42", Price: 100})
} else {
fmt.Printf("product record found: %v", product)
}
}
go run main.go
no product record, creating now...
go run main.go
product record found: { ... }
- 1 回答
- 0 關(guān)注
- 167 瀏覽
添加回答
舉報(bào)