如何通过父ID获取子项的嵌套列表?

时间:2016-10-03 07:22:31

标签: laravel-5.2 parent-child categories

我正在使用baum来获取嵌套的类别列表。我有一个案例,我只想得到一个父母id很少的孩子。我使用了静态函数find . -name "*.png" -exec xattr -c {} \; ,它给了我所有类别的嵌套列表,用空格分隔。我想要相同的响应,但仅限于几个父类别。

我尝试使用下面的代码来获取带有where子句的列表,但它只适用于第一个结果。我有多个parent_id,我需要在空间操作符的数组中列出每个子项。

getNestedList("name", null, "   ")

问题更新

我面临的问题是使用Baum获取后代和自我类别列表只是因为我的数据库输入错误。我对此感到抱歉。现在,我使用$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()); 获取了类别列表,但问题是如何使用descendantsAndSelf()创建嵌套列表?

我尝试$seperator但它只返回嵌套集合。我没有找到任何提供嵌套列表的函数,如函数toHierarchy()。请帮帮我。

2 个答案:

答案 0 :(得分:2)

更新的答案

根据我更新的问题,以下是我的答案,我真正想要做的事情。

要获得父母的后代列表,我使用了以下函数。

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

答案 1 :(得分:1)

你能试试吗?

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