【发布时间】:2019-06-24 19:31:15
【问题描述】:
我得到的结构如下
用户表
id PK
name
email
username
password
用户层次结构表
user_parent_id FK of User
user_child_id FK of User
(Composite primary key)
我写了这两个关系,以便检索谁是用户的父亲,谁是用户的孩子
public function parent()
{
return $this->hasManyThrough(\App\Models\User::class, \App\Models\UserHierarchy::class, 'user_child_id', 'id', 'id', 'user_parent_id');
}
public function children()
{
return $this->hasManyThrough(\App\Models\User::class, \App\Models\UserHierarchy::class, 'user_parent_id', 'id', 'id', 'user_child_id');
}
为了得到所有的孩子,孙子等等,我开发了这个adicional关系,它使用了eager loading
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive.children');
}
到目前为止一切顺利,当我找到一个有 id 的用户时,我可以使用 childrenRecursive 获得所有向下的树。我现在想要实现的是重新使用这些关系来过滤一组特定的结果,我的意思是:当它是某个用户(例如 id 1)时,我想要一个属于的用户集合他的向下树(子递归)和他的第一个直接父母。
$model->where(function ($advancedWhere) use ($id) {
$advancedWhere->whereHas('parent', function ($advancedWhereHas) use ($filterValue) {
$advancedWhereHas->orWhere('user_child_id', $id);
//I want all users that are recorded as his parents
})->whereHas('childrenRecursive', function ($advancedWhereHas) use ($id) {
// Missing code, I want all users that are recorded as his children and downwards
})->get();
这是我正在测试的完整树,上面产生的结果(如果我在 childrenRecursive 上添加类似的orWhere)是它返回具有父子关系的每个用户。例如,用户 2 应该返回除 11 和 12 之外的所有数字,并且它返回除 11 之外的所有数字(因为 11 不是任何人的孩子)
【问题讨论】:
-
你在纠结什么?你有什么错误吗?有什么问题吗?
-
@Script47 没有错误,“我在实现向下树时遇到了麻烦”“我想要一个属于他的向下树(子递归)和他的第一个直接父母的用户集合”,我将用一个 adicional 示例更新问题