Laravel Vue中基于customer_id统计嵌套关联Report最新记录amount总和咨询
实现方案
方案1:数据库子查询统计(性能最优,适合生产环境)
直接在数据库层完成计算,无需加载全量关联数据,推荐优先使用:
// 传入指定的customer_id $customerId = 1; $totalLatestAmount = Project::where('customer_id', $customerId) ->selectRaw('SUM( (SELECT amount FROM reports WHERE reports.project_id = projects.id ORDER BY id DESC LIMIT 1) ) as total_amount') ->value('total_amount');
如果需要同时获取每个项目的最新报告金额单独展示,可以调整为:
$projects = Project::where('customer_id', $customerId) ->addSelect(['latest_amount' => Report::select('amount') ->whereColumn('project_id', 'projects.id') ->orderByDesc('id') ->limit(1) ]) ->get(); // 集合层面直接求和即可 $totalLatestAmount = $projects->sum('latest_amount');
方案2:基于现有hasManyThrough关联处理(适合小数据量场景)
如果数据量不大,可以直接复用你已经定义好的关联实现:
$customer = Customer::with('report')->findOrFail($customerId); $totalLatestAmount = $customer->report ->groupBy('project_id') ->map(fn($reports) => $reports->sortByDesc('id')->first()?->amount) ->sum();
补充说明
- 如果需要过滤掉没有报告的项目,在查询中添加
WHERE EXISTS条件过滤项目即可 - 方案1所有逻辑在数据库层完成,IO开销远低于方案2,数据量超过1000条时优先使用方案1
内容的提问来源于stack exchange,提问作者Mary Tan
相关产品推荐
相关产品推荐

