You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Eloquent查询中orderBy排序失效问题求助

解决Laravel嵌套关联查询中orderBy不生效的问题
  • 修正关联层级的闭包写法,确保排序逻辑精准作用到目标关联模型:
    拆分嵌套关联的闭包结构,明确每层关联的查询范围:

    $pr_data = Category::with(['catproduct' => function ($query) {
        $query->with(['rproduct' => function ($subQuery) {
            $subQuery->where('status', '1')->orderBy('position', 'asc');
        }]);
    }])->where('id', $categoryDetials->id)->get();
    
  • 将排序规则固化到关联模型定义中:
    在rproduct关联所属的模型里,直接给关联添加默认排序,后续加载该关联时自动应用规则:

    // 关联模型中的rproduct方法
    public function rproduct()
    {
        return $this->hasMany(Rproduct::class)->orderBy('position', 'asc');
    }
    

    之后查询只需过滤状态即可:

    $pr_data = Category::with(['catproduct.rproduct' => function ($query) {
        $query->where('status', '1');
    }])->where('id', $categoryDetials->id)->get();
    
  • 检查position字段的数据类型:
    如果position是字符串类型,数字排序会按字符逻辑执行(比如"10"会排在"2"前面),可通过强制转换字段类型修正:

    $subQuery->where('status', '1')->orderByRaw('CAST(position AS UNSIGNED) asc');
    

内容的提问来源于stack exchange,提问作者Sanjay Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 18:42:01