You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
package models
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"go_mqtt/mydb"
|
|
|
|
|
"go_mqtt/utils"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
//gorm:"column:column_name":指定字段在数据库中的列名。
|
|
|
|
|
//gorm:"primaryKey":指定字段为主键。
|
|
|
|
|
//gorm:"autoIncrement":指定字段为自增长。
|
|
|
|
|
//gorm:"unique":指定字段在数据库中唯一。
|
|
|
|
|
//gorm:"not null":指定字段不能为空。
|
|
|
|
|
//gorm:"default:value":指定字段的默认值。
|
|
|
|
|
//gorm:"size:length":指定字段的长度。
|
|
|
|
|
//gorm:"index":指定字段创建索引。
|
|
|
|
|
|
|
|
|
|
type Product struct {
|
|
|
|
|
ID uint `gorm:"primaryKey;autoIncrement"`
|
|
|
|
|
Name string `gorm:"size:255;not null"`
|
|
|
|
|
Price float64
|
|
|
|
|
Category string `gorm:"index"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//func init() {
|
|
|
|
|
// fmt.Println("Product init()")
|
|
|
|
|
// mydb.DB.AutoMigrate(&Product{})
|
|
|
|
|
//}
|
|
|
|
|
|
|
|
|
|
// TableName 会将 Product 的表名重写为 `product`
|
|
|
|
|
func (Product) TableName() string {
|
|
|
|
|
return "product"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func SaveProduct() {
|
|
|
|
|
price := utils.GetRandomFloat64(100, 2000)
|
|
|
|
|
// 创建记录
|
|
|
|
|
product := Product{Name: "Laptop", Price: price}
|
|
|
|
|
result := mydb.DB.Create(&product)
|
|
|
|
|
if result.Error != nil {
|
|
|
|
|
fmt.Println("Failed to create product:", result.Error)
|
|
|
|
|
} else {
|
|
|
|
|
fmt.Println("Product created successfully!")
|
|
|
|
|
}
|
|
|
|
|
}
|