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

Laravel计算最近3条交易平均usage报错:Call to a member function get() on string

问题:计算最近3条交易usage平均值时出现「Call to a member function get() on string」错误

开发账单争议系统时,尝试计算数据库中最近3条交易的usage平均值,出现如下错误:

Call to a member function get() on string

控制器调用代码

$avg = Billing::where('accountNo', $request->referenceCode)
    ->orderBy('dateCreated')
    ->limit(3)
    ->avg('usage')
    ->get()
;

Blade视图展示代码

<tbody class="text-center">
    @foreach ($billing as $b)
    <tr>
        <td class="whitespace-nowrap">{{ date('M Y', strtotime($b->dateCreated)) }}</td>
        <td class="whitespace-nowrap">{{ $b->usage }}m³</td>
        <td class="whitespace-nowrap">₱{{ $b->amount }}</td>
    </tr>

    @endforeach
    <tr style="font-weight: bold; color: #1e293b; background-color: #f1f5f9;">
        <td class="whitespace-nowrap">Average</td>
        <td class="whitespace-nowrap">{{ number_format($avg, 2) }} m³</td>
    </tr>
</tbody>

错误原因与修复方案

核心错误点

  1. 多余的get()调用:avg('usage')方法会直接返回计算完成的平均值(数值或字符串类型),不是查询构建器实例,所以不能链式调用get()——这就是报错的直接原因。
  2. 排序方向错误:orderBy('dateCreated')是按时间正序排列,取到的是最早的3条记录,而非你需要的「最近3条」,应该改为倒序排序。

修复后的代码

方案一:直接查询平均值

$avg = Billing::where('accountNo', $request->referenceCode)
    ->orderBy('dateCreated', 'desc') // 倒序获取最新3条
    ->limit(3)
    ->avg('usage'); // 移除多余的get()

方案二:同时获取交易记录与平均值(更适配视图需求)

如果需要在视图中循环展示这3条交易记录,建议先查询出集合,再基于集合计算平均值:

// 获取最近3条交易记录
$billing = Billing::where('accountNo', $request->referenceCode)
    ->orderBy('dateCreated', 'desc')
    ->limit(3)
    ->get();

// 基于集合计算平均值
$avg = $billing->avg('usage');

这种方式逻辑更清晰,也避免了两次数据库查询(集合的avg()是内存计算,不会额外触发SQL)。


内容的提问来源于stack exchange,提问作者Mirana Chloe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:20:27