【问题标题】:Retrieve data with relations in laravel在 laravel 中检索具有关系的数据
【发布时间】:2021-04-03 22:22:29
【问题描述】:

我想在表格中显示每个实体的名称,但它返回了我

此集合实例上不存在属性 [名称]。

我的控制器

$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>

【问题讨论】:

  • 您的问题不完整,请显示您的数据库架构,您可以使用 dd($users) 检查自己,然后检查珍珠是否具有名称属性

标签: php html database laravel relationship


【解决方案1】:

问题是这一行:blade.php 中的{{ $user-&gt;pearls-&gt;name}}

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

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

    因为pearls 是一个集合,而不是对象! 我认为您已经在用户和珍珠之间执行了一对多的关系,因此,您也应该将 foreach 用于珍珠:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 2019-12-11
      • 2022-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多