Подтвердить что ты не робот

Laravel. Используйте scope() в моделях с отношением

У меня есть две связанные модели: Category и Post.

Модель Post имеет область published (метод scopePublished()).

Когда я пытаюсь получить все категории с этой областью:

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

Я получаю сообщение об ошибке:

Вызов метода undefined 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);
   }

}
4b9b3361

Ответ 1

Вот как вы это делаете:

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

Вы также можете определить отношение:

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

а затем используйте его:

//all posts
$category->posts;

// published only
$category->postsPublished;

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