golang gorm 自定义预加载 SQL 报错invalid query condition

// 首页活动模块区域分类表模型
type LabelType struct {
    Model
    Id           int    `json:"id";gorm:"primary_key"`
    MallId       int    `json:"mall_id"`
    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
}

报 invalid query condition: 0xa6f620

讨论数量: 3

难道golang的问题这么不受关注的么。

3年前 评论

人确实不多!.Model(&labelTypes). 这里是不是错了,应该是labelModel吧

3年前 评论
Frank8866 (楼主) 3年前

Preload("GoodsList", func(query *gorm.DB) *gorm.DB { return query.Order("goods_list.goods_id desc") },是不是要这里加上表名,我手机也不太好试代码!

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!