繁体   English   中英

LaraveL:如何从多对多的关系中获取数据

[英]LaraveL : How to get data from many to many relationship

我有3个user表 - > id,name,password, roles - > id,role, role_user - > role_id,user_id

现在,如果我想在视图页面中显示关联数据意味着与用户相关的角色..我如何在视图中进行? 意味着我想显示用户是否有角色,否则将被检查,否则将取消选中

这是我的控制器:

$users = User::all();
$roles = Role::all();
return view("Permission::assign_role",compact('users','roles'));

查看页面

<table class="table">
    <thead>
    <tr>
        <th>SL No</th>
        <th>Name</th>
        <th>Role</th>
    </tr>
    </thead>
    <tbody>
    <?php $i = 1; ?>
    @foreach($users->roles() as $row)
    <tr>
        <td>{{$i}}</td>
        <td>{{$row->name}}</td>
        <td><input type="checkbox" name="role_id" checked> $role->role</td>
    </tr>

    <?php $i++; ?>

    @endforeach
    </tbody>
</table>

急于加载数据:

$users = User::with('roles')->get();
return view("Permission::assign_role", compact('users'));

在视图中,如果要检查用户是否具有特定角色,则可以执行以下操作:

@if ($user->roles->contains($roleId))

如果您想迭代用户的角色:

@foreach($users->roles as $role)
    {{ $role->name }}

这是我如何用于我的应用程序:

用户模型:

public function roles() {
        return $this->belongsToMany(Role::class);
    }

榜样 :

public function user() {
        return $this->belongsToMany(User::class);
    }

在我的控制器中:

$users = User::all();

在我看来

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM