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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:45:03