ChatGPT解决这个技术问题 Extra ChatGPT

拉拉维尔。在具有关系的模型中使用 scope()

我有两个相关模型:CategoryPost

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

}

J
Jarek Tkaczyk

你可以内联:

$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();
@tptcat 是的。在这种情况下也可以是 Category::has('postsPublished')
干净的问题,干净的答案!
如果查询范围有参数怎么办?

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅