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