我正在使用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');