Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

golang gorm 自定义预加载 正确用法是什么?

// 首页活动模块区域分类表模型
type LabelType struct {
    Model
    Id           int    `json:"id";gorm:"primary_key"`
    MallId       int    `json:"mall_id"`
    Status    int    `json:"-"`
    Name         string `json:"name"`
    Weigh        int    `json:"weigh"`  // 权重
    GoodsList []Goods `gorm:"ForeignKey:LabelId" json:"goods_list"` //查询当前分类下的商品集合
}
type Goods struct {
    Model
    GoodsId         int               `json:"goods_id" gorm:"primary_key"`
    MallId          int               `json:"mall_id"`     // 商城id
    LabelId         int               `json:"label_id"`    // 关联mall_label_type
    GoodsName       string            `json:"goods_name"`  // 商品名称
    CategoryId      int               `json:"category_id"` // 分类id
    SmallImage      string            `json:"small_image"` // 商品缩略图
    Images          string            `json:"images"`
    Category        Category `gorm:"foreignkey:CategoryID" json:"category"` //分类表
}
func (labelModel *LabelType) GetAll(params *request.IndexParams) (labelTypes []*LabelType) {
err := db.Debug().Model(&labelTypes).
        Preload("GoodsList", func(query *gorm.DB) *gorm.DB {
            return query.Order("goods_id desc")
        }).
        Preload("GoodsList.Category").
        Where("mall_id = ? and status = ?", params.MallId, "normal").Order("weigh desc").
        Find(&labelTypes).Error
    if err != nil && err != gorm.ErrRecordNotFound {
        return nil
    }
    return labelTypes
}

加 func(query gorm.DB) gorm.DB { return query.Order("goods_id desc")} 就会报错
invalid query condition: 0xa6f620

不加这个是可以正常查询的


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

问题已解决,原因是因为gorm 用了 v1 和 v2 2个版本


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...