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

Laravel多对多关联下查询活跃客户上月安培数据对应sum_pay总和的问题

正确实现代码

方案1:使用Eloquent关联查询(推荐)

前提是你已经为中间表模型ClientsAmpere定义了和clients、amperes表的关联,代码如下:

use Carbon\Carbon;

// 计算上月的起止日期
$startOfLastMonth = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$endOfLastMonth = Carbon::now()->subMonth()->endOfMonth()->toDateString();

$totalSum = ClientsAmpere::whereHas('clients', function($query) {
    $query->where('status', 1); // 筛选活跃客户
})
->whereHas('amperes', function($query) use ($startOfLastMonth, $endOfLastMonth) {
    $query->whereBetween('date', [$startOfLastMonth, $endOfLastMonth]); // 筛选amperes上月数据
})
->sum('sum_pay'); // 直接在数据库层聚合,性能更高

如果没有为中间表定义关联,直接使用下面的DB联表方案即可。

方案2:使用DB门面联表查询

use Carbon\Carbon;

$startOfLastMonth = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$endOfLastMonth = Carbon::now()->subMonth()->endOfMonth()->toDateString();

$totalSum = DB::table('clients_amperes')
    ->join('clients', 'clients_amperes.clients_id', '=', 'clients.id')
    ->join('amperes', 'clients_amperes.amperes_id', '=', 'amperes.id')
    ->where('clients.status', 1)
    ->whereBetween('amperes.date', [$startOfLastMonth, $endOfLastMonth])
    ->sum('clients_amperes.sum_pay');

两种方案返回的都是你需要的sum_pay总和单个数值。


原有代码错误说明

  • 第一段代码:仅用with做关联预加载不会筛选关联表数据,没有加clients.status=1、amperes.date属于上月的约束条件,还用到了需求不存在的expire_at字段,逻辑完全不匹配
  • 第二段代码:没有关联clients、amperes两张表,完全没加要求的筛选条件,额外做了不必要的分组,返回的是集合而非单个数值
  • 第三段代码:同样没有关联另外两张表加筛选条件,错误使用中间表的created_at而非amperes表的date做时间判断,先全量查数据再计算的方式性能极低

内容的提问来源于stack exchange,提问作者anzlme awed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:21:00