laravel - Build a multi level array from a has many relationship -
i building basic cms in laravel 5.2.
i have 'pages' model. model has 'has many' relationship page can have many sub pages , sub page can have many sub sub pages etc.
my model defined such:
class page extends model { public function children() { return $this->hasmany('app\page', 'page_parent'); } }
my database so
+----+-----------------+------------------------+------------+-------------+ | id | title | description | project_id | page_parent | +----+-----------------+------------------------+------------+-------------+ | 1 | overview | overview page | 1 | 0 | | 2 | overview sub | child page | 1 | 1 | | 3 | young page | kiddy page | 1 | 2 | +----+-----------------+------------------------+------------+-------------+
then in controller have:
public function index() { $pages = page::with('children')->get(); return response()->json($pages, 200); }
what does: returns pages expected, however, pages 1 level deep 1 level in 'children' object so:
[ { "id":1, "title":"overview", "description":"the overview page", "project_id":"1", "page_parent":"0", "children":[ { "id":2, "title":"overview sub", "description":"child page", "project_id":"1", "page_parent":"1", } ] }, { "id":2, "title":"overview sub", "description":"child page", "project_id":"1", "page_parent":"1", "children":[ { "id":3, "title":"very young page", "description":"this kiddy page", "project_id":"1", "page_parent":"2" } ] }, { "id":3, "title":"very young page", "description":"this kiddy page", "project_id":"1", "page_parent":"2", "children":[ ] } ]
what want better front end dev there 1 root json object (the top level page) , 'children' object recurse build multi level tree of pages so:
[ { "id":1, "title":"overview", "description":"the overview page", "project_id":"1", "page_parent":"0", "children":[ { "id":2, "title":"overview sub", "description":"child page", "project_id":"1", "page_parent":"1", "children":[ { [ "id":3, "title":"very young page", "description":"this kiddy page", "project_id":"1", "page_parent":"2", "children":[ ] ] } ] } ] }, ]
i can think of few hacky ways, want know best 'laravel way'. should using accessor or that?
thanks
you can this:
$pages = page::with('children')->get()->tojson();
this works:
$pages = page::with('children')->get()->groupby('page_parent')->tojson();
Comments
Post a Comment