[英]how to eager loading nested relationships in Laravel with custom query?
我有一个评论表,其中包含以下字段:id、body、parent_id。 评论可以有子评论,这就是它使用 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": []
}
]
不使用 eloquent 预加载( with() ),只使用查询生成器,谢谢。
由于可能的答案可能太长,我将其直接发布为答案。 您可以通过在 controller 中创建递归方法来实现此目的,如下所示:
public function commentsLoop($data, $parent = null) {
$comments = [];
foreach ($data as $d) {
if($d['parent_id'] == $parent){
$subComment = commentsLoop($data, $d['id']);
if ($subComment) {
$d['comments'] = $subComment;
}
$comments[] = $d;
}
}
return $comments;
}
然后,您可以从 controller 中的主要方法调用它,如下所示:
public function comments(){
$data = DB::table('comments')->all()->toArray();
return $this->commentsLoop($data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.