我有一个comments
表,其中包含以下字段:id
、body
和parent_id
。comments
可以有subcomments
,这就是为什么它使用parent_id
字段,我想知道如何实现这个嵌套的结果:
[
{
"id": 1,
"body": "test",
"parent_id": null,
"comments": [
{
"id": 2,
"body": "test",
"parent_id": 1,
"comments": [
{
"id": 3,
"body": "test",
"parent_id": 2
},
{
"id": 4,
"body": "test",
"parent_id": 2
}
]
},
{
"id": 5,
"body": "test",
"parent_id": 1,
"comments": []
}
]
},
{
"id": 6,
"body": "test",
"parent_id": null,
"comments": []
}
]
不使用雄辩的热切加载(with()
(,只使用查询生成器,谢谢。
由于可能的答案可能太长,我直接将其作为答案发布。您可以通过在控制器中创建如下递归方法来实现这一点:
public function commentsLoop($comments, $parent = null)
{
$result = [];
foreach ($comments as $comment) {
if ($comment['parent_id'] === $parent) {
$subComment = commentsLoop($comments, $comment['id']);
if ($subComment) {
$comment['comments'] = $subComment;
}
$result[] = $comment;
}
}
return $result;
}
然后,你可以在控制器中的主方法中调用它,如下所示:
public function comments()
{
$comments = DB::table('comments')->all()->toArray();
return $this->commentsLoop($comments);
}
然而,如果你用雄辩来代替,那么在你的模型中建立一种与自我的关系就是答案。