Laravel 8 报错:Property [Name] does not exist on this collection instance 问题求助
解决Laravel中「Property [Name] does not exist on this collection instance」报错
为什么会出现这个错误?
你执行查询时用了->get()方法,这个方法返回的是Eloquent集合(Collection)——简单说就是一个装着多个模型实例的容器,哪怕你的查询只匹配到一条数据,它还是会被打包在集合里。而你在视图里直接写{{$Applications->Name}},是在给集合对象找Name属性,但集合本身没有这个属性,Name是属于集合里单个模型的属性,所以就触发了报错。
两种快速解决方法
1. 获取单个模型(适配你的场景,因为你用where('applications.Id', $id)应该只返回一条数据)
把查询里的->get()换成->first(),这样返回的就是单个Application模型实例,直接访问属性就没问题了:
$Applications = Applications::where('applications.Id', $id) ->select(DB::raw("applications.*,attachments.*,attachmentdetails.*")) ->leftjoin('attachments','applications.Id', '=', 'attachments.application_id') ->leftjoin('attachmentdetails','attachments.id', '=', 'attachmentdetails.attachmentId') ->first(); // 替换get()为first()
视图里正常使用:
{{ $Applications->Name }}
2. 遍历集合(如果查询可能返回多条结果)
如果业务场景下可能返回多条记录,需要在视图里用循环遍历集合中的每个模型:
@foreach($Applications as $application) {{ $application->Name }} @endforeach
额外的重要优化提示
你的查询用了select(DB::raw("applications.*,attachments.*,attachmentdetails.*")),这会导致字段名冲突——比如结果里的Id(来自applications表)和id(来自attachments表)、AttachmentTypeId(来自attachments表)和attachmentTypeId(来自attachmentdetails表),数据库会自动用后面的字段值覆盖前面的,这会导致部分数据丢失。
建议给重复字段指定别名,避免覆盖:
->select(DB::raw(" applications.*, attachments.id as attachment_id, attachments.application_id as attachment_application_id, attachments.AttachmentTypeId as attachment_type_id, attachments.status as attachment_status, attachmentdetails.*, attachmentdetails.attachmentId as detail_attachment_id "))
这样每个字段都有唯一的名称,就能保证数据的准确性了。
内容的提问来源于stack exchange,提问作者developer
相关产品推荐
相关产品推荐

