我正在使用 baum 来获取嵌套的类别列表。我有一个案例,我只想得到几个父母 ID 的孩子。我使用了静态函数
getNestedList("name", null, " ")
,它为我提供了以空格分隔的所有类别嵌套列表。我想要相同的响应,但仅限于少数父类别。
我尝试使用下面的代码来获取带有 where 子句的列表,但它仅适用于第一个结果。我有多个parent_id,我需要用空格运算符将每个子项列在数组中。
$node = Category::where('name', '=', 'Some category I do not want to see.')->first();
$root = Category::where('name', '=', 'Old boooks')->first();
var_dump($root->descendantsAndSelf()->withoutNode($node)->get());
问题更新
我在使用 Baum 获取后代和自我类别列表时遇到的问题只是因为我的数据库中的条目错误。我为此感到抱歉。现在,我使用
descendantsAndSelf()
获取类别列表,但问题是如何使用 $seperator
创建嵌套列表?
我尝试
toHierarchy()
但它只返回嵌套集合。我没有找到任何像函数getNestedList("text", null, " ");
那样提供嵌套列表的函数。请帮我解决这个问题。
更新答案
根据我更新的问题,以下是我真正想做的事情的答案。
为了获取父母的后代列表,我使用了以下函数。
public function getSubcategory($id) {
$node = $this->where('id', $id)->with('children')->first();
$descendant = $node->getDescendantsAndSelf()->toArray();
return $this->CreateNestedList("text", $descendant, null, "-");
}
为了创建嵌套循环,我使用了相同的逻辑 功能
。我在模型中创建了新函数 文件如下。getNestedList()
public function CreateNestedList($column, $data, $key = null, $seperator = ' ') {
$key = $key ?: $this->getKeyName();
$depthColumn = $this->getDepthColumnName();
return array_combine(array_map(function($node) use($key) {
return $node[$key];
}, $data), array_map(function($node) use($seperator, $depthColumn, $column) {
return str_repeat($seperator, $node[$depthColumn]) . $node[$column];
}, $data));
}
你能试试这个吗?
$data=Category::where('id','yourid')->first()->descendants()->get()->pluck('text','id');