表结构
type Category struct { // 商品类别
gorm.Model
Name string `gorm:"type:varchar(20);not null;unique"`
Code string `gorm:"type:varchar(20);not null;unique"`
Goods []Goods `gorm:"foreignkey:Cate;association_foreignkey:Name"`
// 把商品类别中的Name存到商品中的Cate去, 注意的是这个要唯一,当修改商品类别中的Name的时候, 商品中的Cate也会同步修改
}
type Goods struct { // 商品
gorm.Model
Name string `gorm:"type:varchar(30);not null;unique"`
Cate string `gorm:"type:varchar(30);not null"`
Number int `gorm:"default:1;comment:'商品编号'"`
Unit int `gorm:"default:1;comment:'计量单位:1-瓶,2-盒,3-罐,4-杯,5-包,6-袋'"`
}
查询(预加载)Preload我感觉查询就够了
DB = DB.Where("id = ?", c.Param("ID"))
// 进行查询
if err := DB.Preload("Goods").First(&instance).Error; err != nil {
return
}
吐槽
GORM好像只能从一查到多, 怎么在查多的时候可以使用一的数据,这个我没有发现,等发现在加上