gorm 自定义预加载的 正确用法是什么?一直报错: invalid query condition

2020-09-03 15:46:51 +08:00
 ysongyang
// 首页活动模块区域分类表模型
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
}
1225 次点击
所在节点    Go 编程语言
7 条回复
ysongyang
2020-09-03 17:05:18 +08:00
LabelType 代码补全
```
// 首页活动模块区域分类表模型
type LabelType struct {
Model
Id int `gorm:"primary_key" json:"id"`
MallId int `json:"mall_id"`
Name string `json:"name"`
Images string `json:"images"` // 背景图
Status string `json:"-"` // normal 开启 hidden 关闭
Weigh int `json:"weigh"` // 权重, 越大越靠前
CreateTime int `json:"-"`
UpdateTime int `json:"-"`
GoodsList []LitestoreGoods `gorm:"ForeignKey:LabelId" json:"goods_list"` //查询当前分类下的商品集合
}
```
ysongyang
2020-09-03 17:19:46 +08:00
加 func(query gorm.DB) gorm.DB { return query.Order("goods_id desc")} 就会报错
invalid query condition:
不加这个是可以正常查询的
EileenJ
2020-09-03 18:26:58 +08:00
去掉 Model(&labelTypes)试下
ysongyang
2020-09-04 08:59:30 +08:00
@EileenJ 没用的。能使的方法都试过。
Carlgao
2020-09-04 10:30:28 +08:00
你的 ForeignKey:LabelId 写错了吧,难道不是应该是 GoodId 吗,然而在你的 LabelType 结构体里面没有看到这个字段
ysongyang
2020-09-04 14:14:37 +08:00
@Carlgao 我查询的是 模块分类列表,然后列出 模块分类下的商品集合,没毛病吧。而且我也说了呀 加 func(query gorm.DB) gorm.DB { return query.Order("goods_id desc")} 就会报错, 不加这个 是可以正常查出来我想要的数据的呀。
ysongyang
2020-09-04 16:15:02 +08:00
问题已解决!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/703904

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX