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

Laravel如何按关联预约数对Customer集合进行排序

按关联预约数排序客户集合

你需要通过统计每个客户的预约记录数量,再基于这个统计值进行排序,具体实现如下:

完整查询代码

Customer::where('tid', $tid)
    ->with(['reservations']) // 加载客户关联的预约记录
    ->withCount('reservations') // 统计每个客户的预约数,生成`reservations_count`字段
    ->when($request->get('reservation_filter') !== null, function($q) use($request){
        if($request->get('reservation_filter') == 'order by maximum reservations'){
            // 按预约数从多到少排序
            $q->orderByDesc('reservations_count');
        } else {
            // 按预约数从少到多排序
            $q->orderBy('reservations_count');
        }
    })
    ->paginate(20);

关键说明

  • withCount('reservations'):这个方法会自动为每个Customer实例添加reservations_count属性,存储该客户的预约记录总数,这是实现排序的核心。
  • 排序逻辑:
    • 当筛选值为order by maximum reservations时,用orderByDesc实现倒序(预约数多的在前)
    • 其他情况用orderBy实现正序(预约数少的在前)
  • 没有预约记录的客户,reservations_count会被设为0,排序时会正常纳入结果。

内容的提问来源于stack exchange,提问作者Emad Rashad Muhammed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:10:48