检索具有 laravel 中关系的数据

Retrieve data with relations in laravel

我想在我的 table 中显示每个实体的名称,但 returns 我

Property [name] does not exist on this collection instance.

我的控制器

$users = User::with('pearls')->latest()->get();

index.blade.php

<thead>
<tr>
    <th scope="col">SL No</th>
    <th scope="col">Name</th>
    <th scope="col">Email</th>
    @foreach($users as $user)
        <th>{{ $user->pearls->name}}</th>
    @endforeach
    <th scope="col">Actions</th>
</tr>
</thead>

因为pearls是集合,不是对象! 我想你已经在用户和珍珠之间建立了一对多的关系,所以,你也应该对珍珠使用 foreach:

foreach ($user->pearls as $pearl){
  echo $pearl->name;
}

问题出在这一行:blade.php

中的 {{ $user->pearls->name}}

对于 hasMany 关系,您无法像这样检索数据。 任何名称中包含 Many 的关系,例如:hasManybelongsToMany 将始终 return 一个集合对象。

尝试dd($users->pearls),它会return收集数据。 您正在尝试在集合对象上调用 属性 name,而不是从单个模型调用。

当您使用 get() 方法时,您将获得一个集合。在这种情况下,您需要对其进行迭代以获取属性。

@foreach ($user->pearls as $pearl)
    {{ $pearl->name}}
@endforeach

通过使用其索引,您将获得对象之一 属性

@foreach($users as $user)
    <th>{{ $user->pearls[0]->name}}</th>
@endforeach

或者您可以在查询中使用 first() 方法而不是 get() 方法,这样您就可以像 {{ $user->pearls->name}} 一样轻松地调用对象 属性,您还需要使用 one to one 关系,例如 hasOne.