Laravel资源 - 有孩子类别的父母

时间:2018-05-17 09:54:56

标签: php laravel

我想用Laravel资源在父级中加载我的子类别。

我的json是这样的:

    "data": [
    {
        "id": 2,
        "slug": "child-categorie-0",
        "name": "Child Catégorie 0",
        "parent_id": 1
    },
    {
        "id": 3,
        "slug": "child-categorie-1",
        "name": "Child Catégorie 1",
        "parent_id": 1
    },
    {
        "id": 1,
        "slug": "parent-categorie-0",
        "name": "Parent Catégorie 0",
        "parent_id": null
    },
],

我希望如此:

    "data": [
    {
        "id": 1,
        "slug": "parent-categorie-0",
        "name": "Parent Catégorie 0",
        "childrens": [
            {
                "id": 2,
                "slug": "child-categorie-0",
                "name": "Child Catégorie 0",
            },
            {
                "id": 3,
                "slug": "child-categorie-1",
                "name": "Child Catégorie 1",
            }                
        ]

    }
],

应用\ HTTP \资源\ Category.php

public function toArray($request)
{
    return [
        'id' => $this->id,
        'slug' => $this->slug,
        'name' => $this->name,
        'parent_id' => $this->parent_id
    ];
}

控制器

$categories = Category::orderBy('name', 'asc')->get();
return new CategoryCollection($categories);

我是Laravel资源的新手,所以如果有人有解决这个问题的途径,谢谢!

1 个答案:

答案 0 :(得分:0)

我解决了我的问题!

我在我的分类模型中创建了一个关系。

public function childrens()
{
    return $this->hasMany('App\Category', 'parent_id', 'id');
}

在我的类别资源中

public function toArray($request)
{
    return [
        'slug' => $this->slug,
        'name' => $this->name,
        'childrens' => self::collection($this->whenLoaded('childrens'))  
    ];
}

在我的控制器中

$categories = Category::with('childrens')->parents()->orderBy('name','asc')->get();