我有两个相关模型:Category
和 Post
。
Post
模型具有 published
范围(方法 scopePublished()
)。
当我尝试获取具有该范围的所有类别时:
$categories = Category::with('posts')->published()->get();
我收到一个错误:
调用未定义的方法发布()
类别:
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();
不定期副业成功案例分享
Category::whereHas('posts', function ($q) { $q->published(); })->get();
Category::has('postsPublished')