指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

数据库结构如下:

type Product struct {
    ID          uint      `gorm:"primarykey"`
    Name        string    `gorm:"type:varchar(15);default:NULL;comment:名称"`
    CoverImage  string    `gorm:"type:varchar(255);default:NULL;comment:封面图"`
    Description string    `gorm:"type:varchar(255);default:NULL;comment:描述"`
    Detail      string    `gorm:"type:text;default:NULL;comment:详情"`
    Price       string    `gorm:"type:decimal(10, 2);default:NULL;comment:价格"`
    Sales       uint      `gorm:"type:bigint;default:NULL;comment:销量"`
    Remark      uint      `gorm:"type:bigint;default:NULL;comment:评价"`
    Kind        string    `gorm:"type:varchar(255);default:NULL;comment:品类"`
    CreatedAt   time.Time `gorm:"type:timestamp;default:NULL;comment:创建时间"`
    UpdatedAt   time.Time `gorm:"type:timestamp;default:NULL;comment:更新时间"`

    //一对一,注意:references 为主表的外键,foreignKey:为附表的主键,可以大写为struct 字段名,也可以直接小写为数据库对应字段
    //Category   Kind      `gorm:"foreignKey:ID;references:KindId;"`

    //一对多,注意:references 为主表的主键,foreignKey:为附表的外键
    //Attributes []ProductAttribute `gorm:"foreignKey:ProductId;references:ID"`
    Attributes []ProductAttribute `gorm:"foreignKey:product_id;references:id"`
}

type Kind struct {
	ID   uint   `gorm:"primarykey"`
	Name string `gorm:"type:varchar(15);default:NULL;comment:名称"`
}

type ProductAttribute struct {
	ID             uint      `gorm:"primarykey;column:id;"`
	ProductId      string    `gorm:"type:int;default:NULL;comment:产品ID"`
	Attribute      string    `gorm:"type:varchar(255);default:NULL;comment:属性"`
	AttributeValue string    `gorm:"type:varchar(255);default:NULL;comment:属性值"`
	CreatedAt      time.Time `gorm:"type:timestamp;default:NULL;comment:创建时间"`
	UpdatedAt      time.Time `gorm:"type:timestamp;default:NULL;comment:更新时间"`
}

①一对一
//common.Db.Model(&model.InnerProduct{}).Preload("Category").Find(&products)
//common.Db.Model(&model.InnerProduct{}).Joins("Category").Find(&products)

这里Preload和Joins 都可以实现关联查询
②一对多
common.Db.Preload("Attributes").Where("kind = ? and name like ?", res.Kind.Kind, "%"+keywords+"%").Find(&products)
这里只能用Preload 关联,因为 Attributes 是一个slice
--返回--