Laravel miltiple级别与limit()的关系

时间:2016-09-19 07:53:07

标签: laravel laravel-5.2

我对Laravel Eloquent有一些问题,需要你的帮助。 我想显示单个帖子的每个评论的1个回复

这是我的表格

posts (id,title)
id   | title
---------------------
1    | My post
---------------------

comments(id,post_id,comment,parent_id)
id   | post_id | comment         | parent_id
-----------------------------------------
1    | 1       | First comment   | null
-----------------------------------------
2    | 1       | Second comment  | null
-----------------------------------------
3    | null    | 3rd comment     | 1
-----------------------------------------
4    | null    | 4th comment     | 1
-----------------------------------------
5    | null    | 5th comment     | 2
-----------------------------------------
6    | null    | 6th comment     | 2
-----------------------------------------

我的模特(Eloquent)

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('Comment', 'post_id');
    }
}
---------------------
class Comment extends Model
{
    public function reply()
    {
        return $this->hasMany('Comment', 'parent_id');//self relationship
    }
}

我的查询功能

public function getPost($postId){
    $posts = Post::with(['comment.reply'=>function($q){
       $q->limit(1);
    }])
    ->find($postId);

    return $posts;
}

我得到了结果

{[
   id=>1,
   title=>'My post',
   'comments'=>[
       0=>[
         id=>1,
         comment=>'First comment',
         parent_id=>null,
         post_id=>1,
         reply=>[
           0=>[........(comment id:3).......]
         ]
       ],
       1=>[
         id=>2,
         comment=>'Second comment',
         parent_id=>null,
         post_id=>1,
         reply=>null
       ]
   ]
]}

但我想要这样

{[
       id=>1,
       title=>'My post',
       'comments'=>[
           0=>[
             id=>1,
             comment=>'First comment',
             parent_id=>null,
             post_id=>1,
             reply=>[
               0=>[........(comment id:3,4)........]
             ]
           ],
           1=>[
             id=>2,
             comment=>'Second comment',
             parent_id=>null,
             post_id=>1,
             reply=>[
               0=>[........(comment id: 5,6).........]
             ]
           ]
       ]
    ]}

请帮忙!

1 个答案:

答案 0 :(得分:0)

试试这个:

$posts=Post::where(['id'=>1])->with(['comments'=>function($query)
               {
                  $query->with(['replies'=>function($query)
                      {
                            $query->limit(1);
                      }]);

            }])->first(); 
print_r($posts);