2016-10-07 3 views
0

Ich habe drei Modelle:Laravel 5.1: Holen Sie nur die Datensätze des verwandten Modell

  • Kategorie
  • Beitrag
  • Kommentar

Dies sind ihre Implementierungen:

class Category extends \Eloquent { 
    public function posts() { 
     return $this->hasMany('Post'); 
    } 
} 


class Post extends \Eloquent { 
    public function category() { 
     return $this->belongsTo('Category'); 
    } 
    public function comments() { 
     return $this->hasMany('Comment'); 
    } 
} 

class Comment extends \Eloquent { 
    public function post() { 
     return $this->belongsTo('Post'); 
    } 
} 

Ist es möglich, eloquent, t o eine Liste (Array oder Sammlung) aller Kommentare (und nur der Kommentare, ohne Beiträge) zu einer Kategorie zu bekommen? (das bedeutet, bei einer Kategorie alle zugehörigen Beiträge finden und dann alle zugehörigen Kommentare zurückgeben).

Vielen Dank im Voraus!

Antwort

2

Einfach hasManyThrough Bezug auf Ihr Modell Kategorie verwenden:

class Category extends \Eloquent { 
    public function posts() { 
     return $this->hasMany(Post::class); 
    } 
    public function comments() { 
     return $this->hasManyThrough(Comment:class,Post::class); 
    } 
} 

Danach können Sie einfach $category->comments rufen Sie eine Sammlung mit allen Kommentaren zu einer Kategorie mit Bezug zu haben.

Weitere Informationen finden Sie unter https://laravel.com/docs/5.1/eloquent-relationships#has-many-through.

Für Laravel 5.3: https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

+0

Vielen Dank! Ich habe es auf eine ganz andere Art und Weise gemacht, aber es hat genau das, was ich brauche. Vielen Dank –

Verwandte Themen