2016-05-25 36 views
0

我在Laravel 5.2中構建了一個基本的CMS。從一個有很多關係構建多級數組

我有'網頁'模型。這種模式有一個「有很多」與自己的關係作爲一個頁面可以有很多子頁面和子頁面可以有很多子子頁面等

我的模型被定義爲這樣的:

class Page extends Model 
{ 
    public function children() 
    { 
     return $this->hasMany('App\Page', 'page_parent'); 
    } 
} 

我數據庫是像這樣

+----+-----------------+------------------------+------------+-------------+ 
| id | title   | description   | project_id | page_parent | 
+----+-----------------+------------------------+------------+-------------+ 
| 1 | Overview  | The overview page  |   1 |   0 | 
| 2 | Overview sub | Child page    |   1 |   1 | 
| 3 | Very young page | This is the kiddy page |   1 |   2 | 
+----+-----------------+------------------------+------------+-------------+ 

然後在我的控制,我有:

public function index() 
{ 
    $pages = Page::with('children')->get(); 
    return Response()->json($pages, 200); 
} 

這裏做的事情: 這將返回頁面不如預期,但是,頁面是唯一一個深一個層次的「孩子」的對象,像這樣的水平:

[ 
    { 
     "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 is the kiddy page", 
      "project_id":"1", 
      "page_parent":"2" 
     } 
     ] 
    }, 
    { 
     "id":3, 
     "title":"Very young page", 
     "description":"This is the kiddy page", 
     "project_id":"1", 
     "page_parent":"2", 
     "children":[ 

     ] 
    } 
    ] 

我想要什麼 會是什麼對於我的前端開發者來說更​​好的是隻有一個根JSON對象(頂層頁面),然後將'子對象'遞歸到其自身中以構建如此的頁面的多級樹:

[ 
{ 
     "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 is the kiddy page", 
       "project_id":"1", 
       "page_parent":"2", 
       "children":[ 

       ] 
       ] 
      } 
      ] 
     } 
     ] 
    }, 
] 

我可以想到一些黑客的方法,但想知道什麼是最好的'Laravel方式'。我應該使用訪問器還是類似的東西?

感謝

回答

0

你可以這樣說:

$pages = Page::with('children')->get()->toJson(); 

這也適用於:

$pages = Page::with('children')->get()->groupBy('page_parent')->toJson(); 
+0

感謝您的答覆,但是這幾乎是我已經有了,並返回「線性'版本的JSON,而不是我需要的遞歸對象 –

+0

我100%確定它返回多級數組。我有一個具有'parent_id'字段的類別的項目,這也是一個類別。在你的代碼中,你只有' - > get();',你嘗試了' - > get() - > toJson();'? – TheFallen