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

55

У меня есть две связанные модели: 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);
   }

}
Теги:
eloquent
laravel-4

1 ответ

95
Лучший ответ

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

$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();
  • 2
    Кстати, если вы хотите получить ТОЛЬКО там, где вы опубликовали посты: Category::whereHas('posts', function ($q) { $q->published(); })->get();
  • 1
    @tptcat да. Также может быть Category::has('postsPublished') в этом случае

Ещё вопросы

Сообщество Overcoder
Наверх
Меню