如何通过 Parent id 获取 child 的嵌套列表?

How to get a nested list of a child by Parent id?

我正在使用 baum 来获取嵌套的类别列表。我有一个案例,我只想获得几个 parent id 的 child。我使用了静态函数 getNestedList("name", null, "   "),它为我提供了由 space 分隔的所有类别嵌套列表。我想要相同的回复,但只针对少数 parent 个类别。

我尝试使用下面的代码来获取带有 where 子句的列表,但它只适用于第一个结果。我有多个 parent_id 并且我需要使用 space 运算符在数组中列出每个 child。

$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() 但它只是 return 嵌套集合。我没有找到任何提供嵌套列表的函数,如函数 getNestedList("text", null, "   ");。请帮我解决这个问题。

你能试试这个吗?

$data=Category::where('id','yourid')->first()->descendants()->get()->pluck('text','id');

更新的答案

根据我更新的问题,以下是我的回答,我实际上想做的事情。

要获取 parent 的后代列表,我使用了以下函数。

public function getSubcategory($id) {
    $node = $this->where('id', $id)->with('children')->first();
    $descendant = $node->getDescendantsAndSelf()->toArray();
    return $this->CreateNestedList("text", $descendant, null, "-");
}

And to create nested loop I have used the same logic of the function getNestedList(). I have created new function inside my model file as below.

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));
    }