我怎样才能return数据类以对象形式放在laravel上?
How can I return data category in object form on the laravel?
我用laravel 5.6
我的 table 类别是这样的:
我想使用 laravel eloquent 到 select 数据类别,然后它会 return 像这样的对象形式:
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'}
]
},
]
}
]
我该怎么做?
创建具有 children
关系的 Category
模型:
class Category extends Model {
public function children() {
return $this->hasMany(Category::class, 'parent_id');
}
}
然后你可以这样查询:
$categories = Category::whereNull('parent_id')->with('children.children')->get();
我用laravel 5.6
我的 table 类别是这样的:
我想使用 laravel eloquent 到 select 数据类别,然后它会 return 像这样的对象形式:
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'}
]
},
]
}
]
我该怎么做?
创建具有 children
关系的 Category
模型:
class Category extends Model {
public function children() {
return $this->hasMany(Category::class, 'parent_id');
}
}
然后你可以这样查询:
$categories = Category::whereNull('parent_id')->with('children.children')->get();