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


101

我有两个相关模型:CategoryPost

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

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

$categories = Category::with('posts')->published()->get();

我收到一个错误:

调用未定义的方法 published()

类别:

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);
   }

}

Answers:


178

您可以内联:

$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();

6
顺便说一句,如果您只想在哪里发布帖子,请:Category::whereHas('posts', function ($q) { $q->published(); })->get();
tptcat '17

2
@tptcat是的。Category::has('postsPublished')在这种情况下也可以
Jarek Tkaczyk '17

干净的问题,干净的答案!
Mojtaba Hn
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.