我正在使用带有MySQL后端的LARAVEL 4。
我有一个自引用表,其中包含列id、name、type和parent。这里,父级是列Id的外键。表中的数据如下:
id name type parent
1 General group NULL
2 What is..? question 1
3 aa answer 2
4 bb answer 2
5 cc answer 2
6 How is..? question 1
7 ba answer 6
8 bb answer 6
9 Where is..? question 4
10 ca answer 9
11 cb answer 9
12 Who is..? question 6
13 da answer 12
14 db answer 12
15 Specific group NULL
16 When is..? question 15
17 ea answer 16
18 eb answer 16
19 Whome is..? question 2
20 fa answer 19
21 fb answer 19
22 fc answer 19
我希望得到一个函数,使用这个关联数据返回嵌套的JSON。例如:
[{
"id" : 1,
"name" : "Geneal",
"type" : "group",
"children" : [{
"id" : 2,
"name" : "What is..?",
"type" : "question",
"children" : [{
"id" : 3,
"name" : "aa",
"type" : "answer"
},
{
"id" : 4,
"name" : "bb",
"type" : "answer"
},
{
"id" : 5,
"name" : "cc",
"type" : "answer"
}]},
{
"id" : 6,
"name" : "How is..?",
"type" : "question",
"children" : [{
"id" : 7,
"name" : "ba",
"type" : "answer"
},
{
"id" : 8,
"name" : "bb",
"type" : "answer"
}]
}]
... and so on
}]
我已经创建了一个名为Survey
的model
,如下所示:class Survey extends BaseModel{
protected $table = 'questions';
protected $softDelete = false;
public function parent()
{
return $this->belongsTo('Survey', 'parent');
}
public function children()
{
return $this->hasMany('Survey', 'parent');
}
}
调用了controller
,代码如下:
$user = Survey::all();
$parent = $user->parent()->first();
$children = $user->children()->get();
但是我没有得到我在上面提到的JSON
中所提到的正确结果。
print_r($parent->toJson());
仅提供一个层次结构记录(即组和问题,而不是答案)。
同时
print_r($children ->toJson());
只提供问题(不包括组和答案)。
我希望得到具有N层级嵌套的自引用数据完整的JSON格式。
我也尝试过
$user = Survey::with('parent', 'children')->get();
但是发现和上面的$parent一样。
有没有办法让我得到想要的结果呢?
提前感谢。