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