laravel 拉拉维尔。在有关系的模型中使用 scope()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26178315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel. Use scope() in models with relation
提问by Ilya Vo
I have two related models: Category
and Post
.
我有两个相关的模型:Category
和Post
.
The Post
model has a published
scope (method scopePublished()
).
该Post
模型有一个published
范围(方法scopePublished()
)。
When I try to get all categories with that scope:
当我尝试获取该范围内的所有类别时:
$categories = Category::with('posts')->published()->get();
I get an error:
我收到一个错误:
Call to undefined method
published()
调用未定义的方法
published()
Category:
类别:
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);
}
}
回答by Jarek Tkaczyk
You can do it inline:
您可以内联进行:
$categories = Category::with(['posts' => function ($q) {
$q->published();
}])->get();
You can also define a relation:
您还可以定义一个关系:
public function postsPublished()
{
return $this->hasMany('Post')->published();
// or this way:
// return $this->posts()->published();
}
and then:
进而:
//all posts
$category->posts;
// published only
$category->postsPublished;
// eager loading
$categories->with('postsPublished')->get();