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

Laravel Blade循环渲染安装项出现数据重复问题求助

Laravel Blade循环渲染重复问题解决

问题场景与现象

在Laravel Blade模板中渲染合同的可安装项,计划用foreach循环生成包含项名称和数量的<h6>标签:

  • 数据库中仅存在1个安装项,通过dd($itemsInstallation->item)能正确返回该项信息
  • 执行foreach循环时,页面重复渲染同一数据

原错误代码

@foreach ($itemsInstallation as $item)
   <h6>{{ $itemsInstallation->item->name }} -- {{ $itemsInstallation->cuantity }} uds</h6>
@endforeach

问题原因

模型关联配置错误:将合同与可安装项的一对多关联误用了hasOne方法,正确应使用hasMany。关联类型错误导致数据结构不符合循环预期,进而引发重复渲染。

修复方案

修正模型中的关联关系为hasMany后,使用for循环遍历关联的项集合:

@for ($i = 0; $i < count($itemsInstallation->item); $i++)
    <h6>{{ $itemsInstallation->item[$i]->name }} -- {{ $itemsInstallation->item[$i]->cuantity }} uds</h6>
@endfor

更规范的写法(可选)

修正关联后,也可以用foreach直接遍历关联集合,代码更简洁:

@foreach ($itemsInstallation->item as $item)
    <h6>{{ $item->name }} -- {{ $item->cuantity }} uds</h6>
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:50:00