Laravel.在具有关系的模型中使用scope()

Ily*_* Vo 86 laravel eloquent laravel-4

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

Post模型具有published范围(方法scopePublished()).

当我尝试获取该范围的所有类别时:

$categories = Category::with('posts')->published()->get();
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

调用未定义的方法 published()

类别:

class Category extends \Eloquent
{
    public function posts()
    {
        return $this->HasMany('Post');
    }
}
Run Code Online (Sandbox Code Playgroud)

帖子:

class Post extends \Eloquent
{
   public function category()
   {
       return $this->belongsTo('Category');
   }


   public function scopePublished($query)
   {
       return $query->where('published', 1);
   }

}
Run Code Online (Sandbox Code Playgroud)

Jar*_*zyk 159

你可以内联:

$categories = Category::with(['posts' => function ($q) {
  $q->published();
}])->get();
Run Code Online (Sandbox Code Playgroud)

您还可以定义关系:

public function postsPublished()
{
   return $this->hasMany('Post')->published();
   // or this way:
   // return $this->posts()->published();
}
Run Code Online (Sandbox Code Playgroud)

然后:

//all posts
$category->posts;

// published only
$category->postsPublished;

// eager loading
$categories->with('postsPublished')->get();
Run Code Online (Sandbox Code Playgroud)

  • 顺便提一下,如果你只想获得你发布帖子的地方:`Category :: whereHas('posts',function($ q){$ q-> published();}) - > get();` (4认同)
  • @tptcat 是的。在这种情况下也可以是`Category::has('postsPublished')` (2认同)
  • 干净的问题,干净的答案! (2认同)
  • 如果查询范围有参数怎么办? (2认同)