2016-09-19 2 views
0

Ich habe ein Problem mit Laravel Eloquent und brauche deine Hilfe. Ich möchte anzeigen 1 Antworten jedes Kommentars einzelner Beitrag.Laravel multiple Level-Beziehung mit Limit()

Hier ist meine Tabellen

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

Mein Modell (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 
    } 
} 

Meine Abfragefunktion

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

    return $posts; 
} 

Und ich führen erhalten

{[ 
    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 
     ] 
    ] 
]} 

Aber ich will wie diese

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

Bitte kindly Hilfe!

Antwort

0

Versuchen Sie folgendes:

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

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

Vielen Dank für Ihre Antwort. Ich habe es versucht, aber nicht funktioniert. :( –