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);
}
}
Nawiasem mówiąc, jeśli chcesz dostać się TYLKO tam, gdzie publikujesz posty: 'Category :: whereHas ('posts', funkcja ($ q) {$ q-> publishe re(); }) -> get(); ' – tptcat
@tptcat yes. W tym przypadku może też być "Category :: has (" postsPublished ") –