【问题标题】:Laravel. Use scope() in models with relation拉拉维尔。在具有关系的模型中使用 scope()
【发布时间】:2014-11-28 11:23:34
【问题描述】:

我有两个相关的模型: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);
   }

}

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    你可以内联:

    $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')
    • 干净的问题,干净的答案!
    • 如果查询范围有参数怎么办?
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2018-07-20
    • 1970-01-01
    • 2017-02-06
    相关资源
    最近更新 更多