Laravel多级分级用户系统

Laravel Multi-level hierarchical user system

我有一个使用 Laravel 作为后端 API 和 AngularJS 作为前端的应用程序,具有多层用户树,其中用户 "own" 组其他用户。

例如,老板可能拥有主管,而主管又拥有员工。

员工有 "walls" 条帖子和评论。只有员工才有墙。他的树枝中的任何用户都可以 view/post/comment 在他的墙上 - 所以他的直接主管和所有者可以访问他的墙。

我希望将来可以扩展它以在两者之间添加更多 "roles",所以我不想为每种用户类型设置单独的 table。

我查看了自我反映模型,其中用户 table 有一个 parent_id 列。我遇到了困难,因为 Auth::user->with('children') 返回所有用户,忽略模型中设置的关系:

public function children() {
  return $this->hasMany('User', 'parent_id');
}

public function parent() {
  return $this->belongsTo('User', 'parent_id');
}

问题是 - 是否有可用的软件包允许我通过这些分层用户关系自动确定查询范围?

或者您对这样的用户范例有什么建议?我尝试过的所有搜索和我看过的包裹都没有结果。我认为使用嵌套集包对于这项任务来说太复杂了。 None 我看过的 auth 包确实符合这种范例。它们允许角色和权限,但不基于父子关系确定权限范围。

请尝试以下操作 - 这仅适用于 children - 未经测试!

将此添加到您的 User 模型 class

public function scopeBelongingTo($query, $parentId)
{
    return $query->whereHas('parent', function($query) use ($parentId)
    {
        $query->where('id', $parentId);
        $query->orWhereHas('parent', function($query) use ($parentId)
        {
           $query->where('id', $parentId);
            $query->orWhereHas('parent', function($query) use ($parentId)
            {
               $query->where('id', $parentId);
                $query->orWhereHas('parent', function($query) use ($parentId)
                {
                   $query->where('id', $parentId);
                    $query->orWhereHas('parent', function($query) use ($parentId)
                    {
                       $query->where('id', $parentId);
                    });
                });
            });
        });
    });
}

要查找 children(以及 grandchildren、grand-grandchildren 等),请尝试以下操作:

$idOfParent = 1; // Replace this with the ID of a parent you wish to query their children sub children
$users = User::belongingTo($idOfParent)->get();
dd($users->toArray()); // Should output the parent's childrens in the entire hierarchy down to tier 5...

如果这不起作用,请返回错误,我们会从那里看到。

重要 - 这个特定的例子只适用于 5 个级别。要增加级别,我们必须包括 whereHas。在一段关系中可能有一种方法可以做到这一点,但只要您的应用程序很好地分开,就应该很容易将其换掉。

目前,hard-coded 有效的解决方案是向用户模型添加 children 关系:

public function children() {
  return $this->hasMany('User', 'parent_id');
}

...并在 AuthController 中(我希望返回 children):

$children = Auth::user()->children()->with('children', 'children.children')->get();

这提供了 3 个级别的深度,并且可以通过添加 'children.children.children'.

轻松扩展(尽管不仅仅是添加到数据库)

我还可以检查它是否是员工(层次结构的最低级别):

if(empty($children->toArray()) {}

通过将方法添加到自身,选择的答案会更好 -->with('children') 这样每个子结果都会有它的子结果(使其递归)。无需使用在某些情况下可能无法使用的点符号。

public function children() {
   return $this->hasMany('User', 'parent_id')->with('children');
}

而您的 AuthController 将是:

$children = Auth::user()->children()->get();