如何在Laravel中查询指定月份的用户订单数据
解决方案
你可以通过带条件的关联预加载+关联求和实现需求,具体实现如下:
前置说明
默认你的订单表使用created_at字段存储下单时间,如果你用的是自定义日期字段(如order_time),替换下方代码中的对应字段即可。
实现代码
首先定义你要查询的目标年月,再对关联进行条件筛选同时统计订单总额:
// 自定义查询的年份、月份 $targetYear = 2024; $targetMonth = 3; $users = User::query() // 预加载指定月份的订单详情 ->with(['orders' => function ($query) use ($targetYear, $targetMonth) { $query->whereYear('created_at', $targetYear) ->whereMonth('created_at', $targetMonth); }]) // 统计对应用户指定月份的订单总金额,结果存到 month_order_total 字段 ->withSum(['orders as month_order_total' => function ($query) use ($targetYear, $targetMonth) { $query->whereYear('created_at', $targetYear) ->whereMonth('created_at', $targetMonth); }], 'total') ->get();
结果使用
- 遍历
$users即可拿到所有用户列表 - 单用户对象的
month_order_total属性即为该用户对应月份的订单总金额,无订单时值为0 - 单用户对象的
orders属性即为该用户对应月份的所有订单详情
注意你原有代码的错误:
User::with('orders')->get()返回的是用户集合,不能直接调用->orders属性,需要先取单个用户或者遍历集合再操作关联。
内容的提问来源于stack exchange,提问作者ihprince
相关产品推荐
相关产品推荐

