如何在Laravel中创建嵌套的类别列表?
我想创造这样的东西:
- --- Php
- ------拉维尔
- --------- Version
- ------------ V 5.7
- --- Python
- ------德扬戈
- --- Ruby
- .
The fields of my categories table are:
id | name | parent_id
If I have to add another column like depth or something, please tell me.
我正在使用以下代码,但我认为这不是最好的解决方案.此外,我不能把这个功能放在我的观点上.
function rec($id)
{
$model = Category::find($id);
foreach ($model->children as $chield) rec($chield->id);
return $model->all();
}
function main () {
$models = Category::whereNull('parent_id')->get();
foreach ($models as $parent) return rec($parent->id);
}