56
У меня есть две родственные модели: Category
и Post
.Laravel. Используйте scope() в моделях с отношением
Модель Post
имеет published
scope (метод scopePublished()
).
Когда я пытаюсь получить все категории с этой сферы:
$categories = Category::with('posts')->published()->get();
Я получаю сообщение об ошибке:
Call to undefined method
published()
Категория:
class Category extends \Eloquent
{
public function posts()
{
return $this->HasMany('Post');
}
}
Заголовок сообщения:
class Post extends \Eloquent
{
public function category()
{
return $this->belongsTo('Category');
}
public function scopePublished($query)
{
return $query->where('published', 1);
}
}
Кстати, если вы хотите ТОЛЬКО получать, где вы опубликовали сообщения: 'Category :: whereHas ('posts', function ($ q) {$ q-> publishe д(); }) -> get(); ' – tptcat
@tptcat да. Также может быть 'Category :: has ('postsPublished')' в этом случае –