Laravel。在具有关系的模型中使用scope()

时间:2014-10-03 11:40:56

标签: laravel laravel-4 eloquent

我有两个相关模型:CategoryPost

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);
   }

}

1 个答案:

答案 0 :(得分:140)

你可以内联:

$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();