我有两个相关模型:Category
and Post
.
The Post
模型有一个published
范围(方法scopePublished()
).
当我尝试获取该范围内的所有类别时:
$categories = Category::with('posts')->published()->get();
我收到错误:
调用未定义的方法published()
类别:
class Category extends \Eloquent
{
public function posts()
{
return $this->HasMany('Post');
}
}
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)