使用最佳实践
首先我建议你看看
this
托图里尔。作为使用权重生成层次结构数据的最佳实践。
而且你用拉维雄辩的关系作为它的活跃记录
//in Tag Model
public function children()
{
return $this->hasMany('App\Models\Tag', 'parent_id');
}
public function parent(){
return $this->belongsTo('App\Models\Tag', 'parent_id');
}
public function nodes()
{
return $this->hasMany('App\Models\Node', 'node_id', 'node_id');
}
然后你就可以得到结果了
//there should be a relation for node also
Tag::with('parent', 'children.children', 'node')->get();
一种简单的php方法
foreach ($tags as $key => $value) {
$tagTree[$value['tag_id']] = $value;
$tagTree[$value['tag_id']]['child'] = array();
}
foreach ($tagTree as $key => $value) {
if ($value['parent_id'] == 0) {
$root[$key] = &$tagTree[$key];
} else {
$tagTree[$value['parent_id']]['child'][$key] = &$tagTree[$key];
}
//here you can check if is there any node for current tag insert
//$tagTree[$value['parent_id']]['node'][] = ...
}