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

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

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

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

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

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

Вызов неопределенного метода 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);
   }

}

person Ilya Vo    schedule 03.10.2014    source источник


Ответы (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();
person Jarek Tkaczyk    schedule 03.10.2014
comment
Между прочим, если вы хотите ТОЛЬКО попасть туда, где вы опубликовали сообщения: Category::whereHas('posts', function ($q) { $q->published(); })->get(); - person tptcat; 31.01.2017
comment
@tptcat да. Также может быть Category::has('postsPublished') в этом случае - person Jarek Tkaczyk; 01.02.2017
comment
Чистый вопрос, чистый ответ! - person Mojtaba Hn; 12.10.2019