dtrgqjcd877528 2019-01-06 17:08
浏览 241

如何使用Laravel中嵌套的多对多关系从数据库中获取数据

I'm working on Laravel Access Control Level (ACL) system. where is table contains some many to many to relationship. User table has many to many belongsToMany with Role Table and inversely many to many Role has belongsToMany with User table.Again, Role table has many to many belongsToMany relationship with Permission table and inversely Permission has many to many belongsToMany with Role table.

I want to run a query from user table which is fetch the all permissions of a role. this role is assigned to current user through roles table.

Here is my code sample.

User Model

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

Role Model

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

public function permissions()
{
    return $this->belongsToMany(Permission::class);
}

Permission Table

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

I've tried this query using egar loading...

public function hasPermission($permission)
{
   if($this->roles()->with('permissions')->get()->pluck('permissions'))
   {
    return true;
   }
   return false;
} 

But it always return false.

  • 写回答

1条回答 默认 最新

  • douwu8524 2019-01-07 22:08
    关注

    There are many ways to check if one of the roles has given permission.

    One example, add hasPermission method to User.php model

    public function hasPermission($permission = '') {
      if ( empty($permisison) ) {
         return false;
      }
    
      /*
        Find all user roles that have given permission
      */
      $rolesWithPermission = $this
                              ->roles()
                                ->whereHas('permissions', function($query) use ($permission) {
                                  $query->where('name', $permission);
                                })
                              ->get();
    
      /*
        If there is at least one role with given permission,
        user has permission
      */
      return $rolesWithPermission->count() > 0;
    }
    

    Or you can do one query with multiple joins between users, roles and permissions, and filter out the result with where('permissions.name', '=', $permission)

    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思