You need to enable JavaScript to run this app. Laravel报Property [x] does not exist on this collection错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Laravel报Property [x] does not exist on this collection错误如何解决?

问题原因
  • 核心错误是对get()返回值的处理逻辑有误:$this->document->where('document_info_id', $id)->get()本身返回的就是包含所有匹配记录的Eloquent Collection集合对象,赋值时加了[],相当于把整个集合作为第一个元素塞进了$infos数组,此时:
    • $infos[0]是完整的集合,不是单条模型记录
    • 循环里直接用$infos[$i]取到的是集合对象,自然无法直接访问模型的device_name属性
  • 测试时dd($infos[$i])仅在第一次循环$i=0时就终止执行,刚好打印出整个集合,所以会误以为取到了正确的值,实际需要的单条模型记录存储在集合的items属性中。
修复代码方案

方案1:修正赋值逻辑,直接使用集合遍历(推荐)

去掉多余的[],直接接收查询返回的集合即可:

public function export(Request $request, $id)
{
    // 直接获取所有匹配的记录集合,不需要加[]
    $infos = $this->document->where('document_info_id', $id)->get();
    foreach ($infos as $info) {
        $this->handover->create([
            'document_info_id' => $id,
            'room_id' => $request->room_id,
            'device_name' => $info->device_name,
            'device_info' => $info->device_info,
            'unit' => $info->unit,
            'qty' => $info->recommended_unit,
            'note' => $info->note
        ]);
    }
}

方案2:保留现有赋值写法,调整取值逻辑

如果不想修改原有赋值逻辑,需要先从数组中取出集合,再遍历集合内的元素:

public function export(Request $request, $id)
{
    $infos[] = $this->document->where('document_info_id', $id)->get();
    // 先取出数组中存储的集合,再遍历集合内的模型记录
    foreach ($infos[0] as $info) {
        $this->handover->create([
            'document_info_id' => $id,
            'room_id' => $request->room_id,
            'device_name' => $info->device_name,
            'device_info' => $info->device_info,
            'unit' => $info->unit,
            'qty' => $info->recommended_unit,
            'note' => $info->note
        ]);
    }
}
额外优化建议
  • 原有代码重复执行了两次where('document_info_id', $id)查询,一次查count、一次查结果,会产生多余的SQL请求。直接用get()拿到集合后调用$infos->count()即可获取总数,不需要单独查询count。
  • 批量插入数据建议用insert()方法代替循环create(),可减少SQL请求次数,提升性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:45:01