如何在laravel上以对象形式返回数据类别?

时间:2018-03-22 02:30:17

标签: php laravel object eloquent laravel-5.6

我使用laravel 5.6

我的表类别如下:

enter image description here

我想使用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'}
                ]
            },
        ]
    }
]

我该怎么做?

1 个答案:

答案 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();