[英]Getting value from many to many relationship in Laravel
I'm trying to get value from my tables with many to many relationship. 我正尝试从与多对多关系的表中获取价值。 My relation are: User:
我的关系是:用户:
public function roles()
{
return $this->belongsToMany('App\Role',"users_roles","usersid","rolesid");
}
Role: 角色:
public function users()
{
return $this->belongsToMany('App\User',"users_roles","usersid","rolesid");
}
I did this in my view: 我认为:
@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
I'm getting following error: Undefined index: role 我遇到以下错误:未定义索引:角色
But when i do {{$user->roles}}, I get following: 但是当我做{{$ user-> roles}}时,我得到以下信息:
[{"id":1,"role":"Administrator","created_at":null,"updated_at":null,"pivot":{"usersid":4,"rolesid":1}}]
Can anyone tell me where did i go wrong? 谁能告诉我我哪里出错了?
You can do 你可以做
<td>
@if($user->roles)
{{$user->roles->first()->role}}
@else
No role for this user
@endif
</td>
You need to use Eager load when you are fetching the users 获取用户时,需要使用Eager负载
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.