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

Laravel使用get()查询数据报集合属性不存在 first()仅返回首条数据问题

问题原因

Property [agent_name] does not exist on this collection instance 错误的根源是你在Blade视图的循环中,错误地使用了集合对象$mini_reports调用单条数据的属性,而非使用循环遍历出来的单条记录变量$mini_report。

  • DB::table()->get()返回的是多条记录组成的集合对象,本身不存在表字段对应的属性
  • 你写的$mini_reports->agent_name是尝试从集合里取属性,自然会报错;换成first()后返回单条对象,属性调用就没问题,但只能拿到第一条数据。

解决方法

直接修正Blade视图中的循环变量即可,同时修正序号写死的问题:
把<tbody>部分的代码替换为以下内容:

<tbody>
    @if ($mini_reports->isNotEmpty())
        @foreach ($mini_reports as $key => $mini_report)    
        <tr>
            <th scope="row">{{ $key + 1 }}</th>
            <td>{{ $mini_report->agent_name }}</td>
            <td>{{ optional(\App\Action::find($mini_report->action))->action_name }}</td>
            <td>{{ $mini_report->amount }}</td>
            <td>{{ \Carbon\Carbon::parse($mini_report->created_at)->diffForHumans() }}</td>
        </tr>
        @endforeach
    @endif
</tbody>

优化建议

  1. 避免在循环中执行数据库查询:你当前在循环里每次都查询Action表,会产生N+1性能问题,可以在控制器查询时用join关联Action表,直接把action_name查出来再传给视图
  2. 用optional()包裹关联查询结果,避免action不存在时抛出错误
  3. 如果你给mini_statements表建立了对应的模型,建议用模型查询代替DB门面写法,代码可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:06:03