gorm join 多表重复字段as
产品模型
type ProductAttribute struct {
Id int `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT"`
Name string `json:"name" gorm:"column:name"` // 名称
OrderBy int `json:"orderBy" gorm:"column:order_by"` // 排序
IndustryId int `json:"industryId" gorm:"column:industry_id"` // 分类id
Status int `json:"status"` // 状态
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
分类模型
type Cate struct {
Id int `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT"`
Name string `json:"name" gorm:"column:name"` // 分类名称
OrderBy int `json:"orderBy" gorm:"column:order_by"` // 排序
Status int `json:"status"` // 状态
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
扫描到此结构体
type ProductAttribute struct {
Id int `json:"id" `
Name string `json:"name" ` // 名称
OrderBy int `json:"orderBy"` // 排序
CateId int `json:"cateId" ` // 分类id
CateName string `json:"cateName"` // 分类名称
Status int `json:"status"` // 状态
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
查询
table := orm.Eloquent.Table(models.ProductAttribute{}.TableName() +" AS p").Select("p.*,i.name AS cate_name").Debug().Joins("left join "+models.Cate{}.TableName()+" AS i ON p.cate_id=i.id")
if req.Name != "" {
table = table.Where("p.name like ?","%"+req.Name+"%")
}
if err = table.Offset((pageIndex -1) * pageSize).Limit(pageSize).Order("p.order_by desc,p.created_at desc").Find(&attribute).Count(&count).Error; err != nil {
log.Println(err.Error())
}
注意:此出i.name AS cate_name 是带下划线的,不是驼峰,是映射返回值结构体,并且因为查找的时候struct字段中的大写会被转义成“_”,所以别名也要将大写转为“_”,这个折腾了好久。

