2014-10-03 13 views
56

Mam dwa powiązane modele: Category i Post.Laravel. Użyj scope() w modelach z relacją

Model Post ma zasięg published (metoda scopePublished()).

Kiedy próbuję uzyskać wszystkie kategorie z tego zakresu:

$categories = Category::with('posts')->published()->get(); 

pojawia się błąd:

Call to undefined method published()

Kategoria:

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

postu:

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


    public function scopePublished($query) 
    { 
     return $query->where('published', 1); 
    } 

} 

Odpowiedz

99

W ten sposób można zrobić go inline:

$categories = Category::with(['posts' => function ($q) { 
    $q->published(); 
}])->get(); 

Można również zdefiniować relację:

public function postsPublished() 
{ 
    return $this->hasMany('Post')->published(); 
    // or this way: 
    // return $this->posts()->published(); 
} 

a następnie użyć go:

//all posts 
$category->posts; 

// published only 
$category->postsPublished; 

// eager loading 
$categories->with('postsPublished')->get(); 
+1

Nawiasem mówiąc, jeśli chcesz dostać się TYLKO tam, gdzie publikujesz posty: 'Category :: whereHas ('posts', funkcja ($ q) {$ q-> publishe re(); }) -> get(); ' – tptcat

+0

@tptcat yes. W tym przypadku może też być "Category :: has (" postsPublished ") –

Powiązane problemy