56
我有两个相关型号:Category
和Post
。 (方法scopePublished()
)。Laravel。在具有关系的模型中使用范围()
当我试图让与该范围内的所有类别:
$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);
}
}
顺便说一句,如果你只想得到你发布的帖子:'Category :: whereHas('posts',function($ q){$ q-> publishe d(); }) - > get();' – tptcat 2017-01-31 18:21:07
@tptcat是的。在这种情况下,也可以是'Category :: has('postsPublished')' – 2017-02-01 00:16:24