我有两个相关模型:Category
和 Post
。
Post
模型有一个 published
范围(方法 scopePublished()
)。
当我尝试获取该范围内的所有类别时:
$categories = Category::with('posts')->published()->get();
我收到错误:
Call to undefined method
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);
}
}
最佳答案
您可以内联完成:
$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();
关于拉拉维尔。在具有关系的模型中使用scope(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26178315/