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

Laravel 拉雷维尔。在具有关系的模型中使用scope(),laravel,laravel-4,eloquent,Laravel,Laravel 4,Eloquent,我有两个相关的模型:Category和Post Post模型有一个published范围(方法scopePublished()) 当我尝试获取该范围内的所有类别时: $categories = Category::with('posts')->published()->get(); 我得到一个错误: 调用未定义的方法published() 类别: class Category extends \Eloquent { public function posts() {

我有两个相关的模型:
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);
   }

}
帖子:

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

}
您可以在线执行此操作:

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

顺便说一句,如果您只想获取已发布帖子的位置:
Category::whereHas('posts',function($q){$q->published();})->get()@tptcat是。也可以是
Category::has('postsPublished')
在这种情况下,干净的问题,干净的答案!