【问题标题】:How to fetch data from database using nested many to many relationships in Laravel如何在 Laravel 中使用嵌套的多对多关系从数据库中获取数据
【发布时间】:2019-01-08 06:08:31
【问题描述】:

我正在开发 Laravel Access Control Level (ACL) 系统。表在哪里包含一些many to many 关系。 User 表具有多对多 belongsToManyRole 表,反之多对多 Role 具有 belongsToManyUser 表。同样,Role 表具有多对多 belongsToMany 与 @ 的关系987654332@ 表和相反的Permission 具有多对多belongsToManyRole 表。

我想从用户表中运行一个查询来获取角色的所有权限。该角色通过角色表分配给当前用户。

这是我的代码示例。

用户模型

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

榜样

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

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

权限表

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

我已经使用 egar loading 尝试过这个查询...

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

但它总是return false

【问题讨论】:

  • 你试过dd( $this->roles()->with('permissions')->get() )吗?此外,在相同的方法中,您永远不会使用 $permission 变量
  • 是的,它显示了一个集合
  • 是空集合吗?如果有角色,你能检查这些角色是否有任何权限吗?或者将dd()的值添加到问题中
  • $data=Auth::user()->roles()->with('permissions')->get()->pluck('permissions'); 这会返回一个集合。但是现在如果我想添加 where 条件我该怎么做?
  • 可以用filter()method过滤掉结果集合。

标签: php laravel


【解决方案1】:

有很多方法可以检查其中一个角色是否已授予权限。

一个例子,在User.php模型中添加hasPermission方法

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;
}

或者您可以在usersrolespermissions 之间进行一次查询,并使用where('permissions.name', '=', $permission) 过滤掉结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 2015-04-05
    相关资源
    最近更新 更多