繁体   English   中英

此集合实例上不存在属性 [图像]。 / Laravel - with() 方法

[英]Property [image] does not exist on this collection instance. / Laravel - with() Method

我从 controller 获得了关系数据,但不能在刀片中使用

Controller..

$employees = Post::where('user_id', $user_id)->with('people')->get();

刀片,我在 foreach 中使用,例如..

$employee->people->image

但它给出了错误

此集合实例上不存在属性 [图像]。

当我 dd($employees)

在此处输入图像描述

问题是变量$employee(包含model Post btw)与我假设的人有1:N的关系

这意味着您必须循环关系返回的人员集合

例如

@foreach($employees as $employee)
   @foreach($employee->people as $person)
      {{ $person->image }}
   @endforeach
@endforeach

您必须 foreach 人的关系,您正在收集该帖子的人,因此您必须 foreach 它,因为关系返回数组,每个帖子的所有人。

@foreach($employees as $employee)
   @foreach($employee->people as $user)
      {{ $user->image }}
   @endforeach
@endforeach

如果你只想要一个你可以使用的人

$employee->people->first()->image

你应该使用这种方式

@if( $employee->people->first()->image)
    {{ $employee->people->first()->image }}
@endif

请检查您发布的 model 是否定义了关系 function?

public function people() {
        return $this->hasMany(people::class); // Add localID and foreign_key ID as param if requires
 }

还要检查图像属性是否存在

请检查此集合实例上不存在属性 [标题]希望对您有所帮助

在这种情况下,每个帖子都有很多人。 因此,您需要指定要从哪些人那里获取信息。 例如,此代码可以工作:

$employee->people->first()->image

因为你从第一批人那里得到了图像。 但我不推荐此代码,因为您正在获取所有人员的帖子并且只使用其中一个并且它没有经过优化。

但是,如果您想向所有人展示使用此功能:

@foreach($employees as $employee) 
    @foreach($employee->people as $person)
        {{ $person->image }}
    @endforeach
@endforeach

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM