在User
型号I中添加了一个名为supervisor
的列,该列可以为每个用户保存另一个 user_id 。
实际上,每个用户可以拥有该列指定的主管用户。
为此,我添加了这样的hierarchical
方法:
protected function hierarchical($users)
{
$users = $users->toArray();
$nestedKeys = array();
foreach ($users as $key => $node) {
$supervisor_id = $node['supervisor']['user_id'];
$index = array_search($supervisor_id, array_column($users, 'user_id'));
if (!is_null($supervisor_id) && $index != -1) {
$users[$index]['children'][] = $node;
$nestedKeys[] = $node['user_id'];
}
}
return $users;
}
该方法接受一个集合的$users
,例如来自User::all()
,它创建了这样的响应,但结果不是我想要的:
[
{
"user_id": 1,
"supervisor": null,
"name": "ahmad",
"family": "badpey",
"full_name": "ahmad badpey",
"children": [
{
"user_id": 7,
"supervisor": {
"user_id": 1,
"name": "ahmad",
"family": "badpey",
"full_name": "ahmad badpey"
},
"name": "ali",
"family": "nasiri arani",
"full_name": "ali nasiri arani"
},
{
"user_id": 8,
"supervisor": {
"user_id": 1,
"name": "ahmad",
"family": "badpey",
"full_name": "ahmad badpey"
},
"name": "مصطفی",
"family": "زاهدی",
"full_name": "مصطفی زاهدی"
}
]
},
{
"user_id": 7,
"supervisor": {
"user_id": 1,
"name": "ahmad",
"family": "badpey",
"full_name": "ahmad badpey"
},
"name": "ali",
"family": "nasiri arani",
"full_name": "ali nasiri arani"
},
{
"user_id": 8,
"supervisor": {
"user_id": 1,
"name": "ahmad",
"family": "badpey",
"full_name": "ahmad badpey"
},
"name": "مصطفی",
"family": "زاهدی",
"full_name": "مصطفی زاهدی",
"children": [
{
"user_id": 9,
"supervisor": {
"user_id": 8,
"name": "مصطفی",
"family": "زاهدی",
"full_name": "مصطفی زاهدی"
},
"name": "حسین",
"family": "قناتی",
"full_name": "حسین قناتی"
}
]
},
{
"user_id": 9,
"supervisor": {
"user_id": 8,
"name": "مصطفی",
"family": "زاهدی",
"full_name": "مصطفی زاهدی"
},
"name": "حسین",
"family": "قناتی",
"full_name": "حسین قناتی"
}
]
您可以看到创建的结构是不正确的,因为下属用户再次分开。
最适合创建类似结构的模型的最佳批准是什么?
这是我在ruby上尝试的东西,但不是拉拉维尔(Laravel2关系..
public函数主管(({ 应用程序/用户::}
公共功能reportees(({ App/user :: Hasmany(App/user :: class(}
请更正任何语法错误,然后尝试一下,看看是否可以做您要寻找的
这种类型的关系是树结构或嵌套集,用户的节点和叶子表示。顶部是老板男人,或根节点,其他所有人都在他下方分支。
这是我建议您考虑的软件包:Eloquent-Tree
您可以使用:
从任何节点遍历两个方向的树$collection = $node->findAncestors()->get();
$collection = $node->findDescendants()->get();
取得所有关系只是:
Tree::getLeaves();
以及生成树的结果:
Tree::mapArray(
array(
array(
'children' => array(
array(
'children' => array(
array(
'children' => array(
array(
'children' => array()
),
array(
'children' => array()
)
)
),
array(
'children' => array()
)
)
),
array(
'children' => array()
)
)
),
array(
'children' => array()
),
array(
'children' => array()
)
)
);
可以在此处找到另一个流行的解决方案:laravel-nestedset