【发布时间】:2018-06-08 03:07:05
【问题描述】:
我正在尝试使用 Laravel 从数据库中获取所有父子数据。在父级中也会有嵌套的父级和子级。这就像一个多层次的东西。我面临的问题是使用循环获取所有这些信息。下面是我的代码。
$totalchild = self::getParentChildren($parent->id);
public function getParentChildren($parent) {
$totalChild = array();
$child = Permission::where('status', 1)->where('parentid', '=', $parent)->pluck('permissionid')->toArray();
$totalChild = $child;
foreach($child as $childs){
$innerChild[] = self::getChildren($childs);
$totalChild = array_push($totalChild, $innerChild);
}
return $totalChild;
}
我得到的错误是“array_push() 期望参数 1 是数组,给定整数”。我不知道那里出了什么问题。基本上我试图在这个父母 ID 下获取所有父母 ID 和孩子 ID。谢谢!
编辑:数据库示例如下。
id name parentid
1 master 0
2 parent A 1
3 parent B 1
4 child A 2
5 child B 2
6 child C 3
7 child A_A 4
8 child A_B 4
假设我想让所有父母和孩子都在这个主父母 id 1 下。
代码更新: 我想出了另一个,但我不知道为什么它只返回第一层。它并没有把它下面的所有父母和孩子都归还给我。
public function getChildren($parent, $tree_string=array()) {
$tree = array();
$tree = Permission::where('status', 1)->where('parentid', $parent)->pluck('permissionid')->toArray();
if(count($tree)>0 && is_array($tree)){
$tree_string=array_merge($tree_string,$tree);
}
foreach ($tree as $key => $value) {
self::getChildren($value, $tree_string);
}
return $tree_string;
}
$totalchild = self::getChildren($parent->id); // returns me the first layer only
【问题讨论】:
-
请分享数据库结构和一些示例数据。
-
已添加数据库,谢谢。