如何在Laravel中使用有说服力的关系在视图中显示两个表数据

时间:2021-12-30 20:16:22

I have two Table names are User and Role Table. I have set manyTomany relations between them using pivot table name Role_User in Laravel Eloquent. Now, I want to show both table data in together a view using Eloquent Relationship.(e.g. I want to show in my view a user from users table contain which role in roles table )

我有两个表名:User和Role Table。我在Laravel中使用pivot表名称Role_User设置了许多它们之间的任意关系。现在,我想用雄辩的关系来展示这两个表数据。我想在我的视图中显示用户表中的用户包含了角色表中的哪个角色

Here, is my eloquent relations.

这里,是我雄辩的亲戚。

public function roles()
{
    return $this->belongsToMany('App\Role');
}
public function users()
{
    return $this->belongsToMany('App\User');
}

My, Eloquent Relationship Query.

我的,雄辩的关系查询。

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

    return view('admin',compact('users'));

I'm try in my View.

在我看来我很努力。

    @foreach($users as $user)
    <tr>
        <td>{{$user->name}}</td>
        <td>{{$user->email}}</td>
        <td>{{$user->roles->name}}</td>
        <td></td>
    </tr>
    @endforeach

2 个解决方案

#1


2  

When you call $user->roles, you get a collection of the roles back. So if you want to display them all in a single string, all you have to do is implode the collection on that string:

当您调用$user->角色时,您将得到一个角色集合。如果你想把它们都显示在一个字符串中,你所要做的就是内爆这个字符串上的集合:

<td>{{$user->roles->implode('name', ', ')}}</td>

< td > { { $ user - >角色- >内爆('名称',',')} } < / td >

#2


0  

Your $user->rules is instance of Collection of Role model. You can use one more foreach:

您的$user->规则是角色模型集合的实例。你可以多使用一个foreach:

@foreach($users as $user)
    //do something with user
    @foreach($user->roles as $role)
        {{$role->name}}
    @endforeach
@endforeach

#1


2  

When you call $user->roles, you get a collection of the roles back. So if you want to display them all in a single string, all you have to do is implode the collection on that string:

当您调用$user->角色时,您将得到一个角色集合。如果你想把它们都显示在一个字符串中,你所要做的就是内爆这个字符串上的集合:

<td>{{$user->roles->implode('name', ', ')}}</td>

< td > { { $ user - >角色- >内爆('名称',',')} } < / td >

#2


0  

Your $user->rules is instance of Collection of Role model. You can use one more foreach:

您的$user->规则是角色模型集合的实例。你可以多使用一个foreach:

@foreach($users as $user)
    //do something with user
    @foreach($user->roles as $role)
        {{$role->name}}
    @endforeach
@endforeach