Laravel如何按带WHERE条件的关联关系统计数降序排序
实现方案
该需求完全可以实现,你可以使用Laravel提供的withCount方法完成带条件的关联计数,再基于计数字段排序即可,具体实现如下:
基础实现代码
$places = Place:: // 先统计符合条件的关联mytickets数量,会自动生成mytickets_count属性 withCount([ 'mytickets' => function($q) use ($from, $to) { $q->whereBetween('used_at', [$from, $to]); } ]) ->with([ 'mytickets' => function($q) use ($from, $to) { $q->whereBetween('used_at', [$from, $to]); } ]) // 按关联数量降序排序 ->orderBy('mytickets_count', 'desc') ->get();
优化写法(避免重复写过滤逻辑)
你可以将公共的过滤闭包抽离出来复用,减少冗余代码同时避免两边条件不一致的问题:
// 抽离公共的过滤条件 $ticketFilter = function($q) use ($from, $to) { $q->whereBetween('used_at', [$from, $to]); }; $places = Place:: withCount(['mytickets' => $ticketFilter]) ->with(['mytickets' => $ticketFilter]) ->orderBy('mytickets_count', 'desc') ->get();
说明
withCount会为每个查询到的Place模型生成一个{关联名}_count格式的属性,值为满足条件的关联数据条数- 如果你不需要返回关联的mytickets具体内容,只需要排序和计数的话,可以删除
with部分的代码,进一步提升查询性能
内容的提问来源于stack exchange,提问作者anderlaini
相关产品推荐
相关产品推荐

