我正在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":[
]
}
]
我想要什么 对我的前端dev来说更好的是只有一个根JSON对象(顶级页面),然后是' children'对象递归到自身以构建页面的多级树,如下所示:
[
{
"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":[
]
]
}
]
}
]
},
]
我可以想到一些hacky方式,但想知道什么是最好的Laravel方式'。我应该使用访问器还是类似的东西?
由于
答案 0 :(得分:0)
你可以这样做:
$pages = Page::with('children')->get()->toJson();
这也有效:
$pages = Page::with('children')->get()->groupBy('page_parent')->toJson();