拉拉维尔.在具有关系的模型中使用 scope() [英] Laravel. Use scope() in models with relation

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

问题描述

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

I have two related models: Category and Post.

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

The Post model has a published scope (method 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');
    }
}

发帖:

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

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

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