一对多关联查询,如何用副表中统计出来的字段来进行排序

$csMerchant = CsMerchant::query()
    ->where('status', CsMerchant::STATUS_ON)
    ->where('audit_status', CsMerchant::AUDIT_STATUS_SUCCESS)
    ->with(['csGoods' => function ($query) {
        $query->where('status', CsGoods::STATUS_ON)
            ->where('audit_status', CsGoods::AUDIT_STATUS_SUCCESS)
            ->groupBy('cs_merchant_id')
            ->select('cs_merchant_id', DB::raw('SUM(sale_count_yesterday) AS yesterday_total_sals'))
    }])
    ->get();

请问如上写法,如何用 yesterday_total_sals 字段来进行排序呢,如何改造,请指教

改造后代码如下:

$csMerchant = CsMerchant::query()
      ->where('status', CsMerchant::STATUS_ON)
      ->where('audit_status', CsMerchant::AUDIT_STATUS_SUCCESS)
      ->withCount(['csGoods as yesterday_total_sals' => function ($query) {
           $query->where('status', CsGoods::STATUS_ON)
               ->where('audit_status', CsGoods::AUDIT_STATUS_SUCCESS)
               ->select(DB::raw("sum(sale_count_yesterday)"));
           }])
      ->orderBy('yesterday_total_sals', 'desc')
      ->get();

感谢 郝合心 同学的回答

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案
Client::withCount(['consumptions as consumptions_sum' => function($query){
    $query->select(DB::raw("sum(total_money) as consumptionssum"));
}])
->orderby('consumptions_sum','desc')
->limit(3)
->get();

我本地试了下 这样应该可以满足你的需求

4年前 评论
一个人的江湖 (楼主) 4年前
讨论数量: 3
Client::withCount(['consumptions as consumptions_sum' => function($query){
    $query->select(DB::raw("sum(total_money) as consumptionssum"));
}])
->orderby('consumptions_sum','desc')
->limit(3)
->get();

我本地试了下 这样应该可以满足你的需求

4年前 评论
一个人的江湖 (楼主) 4年前

order by sum(sale_count_yesterday) sql是这么写的

4年前 评论

要用join ,with应该不可以,他是两条语句

4年前 评论
Client::withCount(['consumptions as consumptions_sum' => function($query){
    $query->select(DB::raw("sum(total_money) as consumptionssum"));
}])
->orderby('consumptions_sum','desc')
->limit(3)
->get();

我本地试了下 这样应该可以满足你的需求

4年前 评论
一个人的江湖 (楼主) 4年前

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