我使用laravel 5.6
我的表类别如下:
我想使用laravel eloquent选择数据类别,然后它会以这样的对象形式返回:
categories: [
{
name: 'England',
children: [
{
name: 'Chelsea',
children: [
{name: 'Hazard'},
{name: 'Morata'}
]
},
{
name: 'Manchester United',
children: [
{name: 'Pogba'},
{name: 'Lukaku'}
]
}
]
},
{
name: 'Spain',
children: [
{
name: 'Real Madrid',
children: [
{name: 'Ronaldo'},
{name: 'Bale'}
]
},
{
name: 'Barcelona',
children: [
{name: 'Messi'},
{name: 'Suarez'}
]
},
]
}
]
我该怎么做?
答案 0 :(得分:3)
创建Category
关系为children
的模型:
class Category extends Model {
public function children() {
return $this->hasMany(Category::class, 'parent_id');
}
}
然后你可以这样查询:
$categories = Category::whereNull('parent_id')->with('children.children')->get();