2016-09-19 68 views
0

我有一些Laravel雄辯問題,需要您的幫助。 我想顯示1條回覆每條評論單個帖子Laravel與限制級別關系()

這裏是我的表

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 
----------------------------------------- 

我的模型(雄辯)

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).........] 
      ] 
      ] 
     ] 
    ]} 

敬請幫助!

回答

0

試試這個:

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

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

感謝您的答覆。我嘗試過,但沒有工作。 :( –