【问题标题】:Laravel Resource - Parents with Childrens CategoriesLaravel 资源 - 有孩子的父母类别
【发布时间】:2018-05-18 15:47:20
【问题描述】:

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

    }
],

App\Http\Resources\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 资源的新手,所以如果有人有解决这个问题的方法,谢谢!

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    我解决了我的问题!

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多