这是我的标签表:
id name parent
--------------------------
1 parent1 null
2 a parent1
3 b parent1
4 parent2 null
5 c parent2
6 d parent1
7 parent3 null
8 e parent3
9 f parent2
我怎样才能拥有一个集合,每个标签都放在其父标签下?我的意思是:
Collection {#499 ▼
#items: array:22 [▼
0 => tag {#524 ▶} //parent1
1 => tag {#525 ▶} //a
2 => tag {#526 ▶} //b
3 => tag {#527 ▶} //d
4 => tag {#528 ▶} //parent2
5 => tag {#529 ▶} //c
6 => tag {#530 ▶} //f
7 => tag {#530 ▶} //parent3
8 => tag {#530 ▶} //e
]
}
谢谢。
最佳答案
给定一个模型 Item
与自身的关系:
class Item extends model {
public function children() {
// parent being a foreign key
return $this->hasMany(__CLASS__, 'parent', 'id');
}
}
$items = Item::with('children')->get();
关于php - 按父级对 Eloquent 集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51377994/