我正试图从我的桌子中获得多对多关系的价值。 我的关系是: 用户:
public function roles()
{
return $this->belongsToMany('App\Role',"users_roles","usersid","rolesid");
}
作用:
public function users()
{
return $this->belongsToMany('App\User',"users_roles","usersid","rolesid");
}
我在我的观点中这样做了:
@foreach($users as $user)
<?php $i++; ?>
<tr>
<td>{{ $i }}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->roles->role}}</td>
<tr>
@endforeach
我收到以下错误: 未定义的索引:角色
但是当我做{{$ user-&gt; roles}}时,我得到以下信息:
[{"id":1,"role":"Administrator","created_at":null,"updated_at":null,"pivot":{"usersid":4,"rolesid":1}}]
谁能告诉我哪里出错?
答案 0 :(得分:0)
你可以做到
<td>
@if($user->roles)
{{$user->roles->first()->role}}
@else
No role for this user
@endif
</td>
您在获取用户时需要使用Eager load