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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:46:26  来源:igfitidea点击:

Laravel. Use scope() in models with relation

laravellaravel-4eloquent

提问by Ilya Vo

I have two related models: Categoryand Post.

我有两个相关的模型:CategoryPost.

The Postmodel has a publishedscope (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();