Laravel。在与关系的模型中使用scope() [英] Laravel. Use scope() in models with relation

查看:147
本文介绍了Laravel。在与关系的模型中使用scope()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相关模型:类别发布

I have two related models: Category and Post.

发布模型已发布范围(方法 scopePublished())。

当我尝试获得所有范围的类别:

When I try to get all categories with that scope:

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

我收到错误:


调用未定义的方法 published()

类别:

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

发布: p>

Post:

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


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

}


推荐答案

这是你如何进行内联:

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

然后使用它:

//all posts
$category->posts;

// published only
$category->postsPublished;

// eager loading
$categories->with('postsPublished')->get();

这篇关于Laravel。在与关系的模型中使用scope()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆