【问题标题】:Using a query scope in a collection laravel在集合 laravel 中使用查询范围
【发布时间】:2015-09-05 12:44:27
【问题描述】:

我的关联模型如下所示(已编辑无关代码):

class Association extends Model
{
    public function members() {
        return $this->hasMany('App\Member');
    }

}

我的会员模型如下所示:

class Member extends Model
{
    public function scopeActive($query) {
        return $query->where('membership_ended_at', Null);
    }
    public function scopeInactive($query) {
        return $query->whereNotNull('membership_ended_at');
    }
}

这就是我想要做的:

$association = Association::find(49);
$association->members->active()->count();

现在,我知道查询和集合之间存在区别。但我基本上要问的是,是否有某种类似的收藏范围。当然,最佳解决方案是不必编写两个活动方法,而是将一个用于两个目的。

【问题讨论】:

  • $association->members()->active()->count(); 工作吗?
  • 哇。我想我被它愚弄了,它允许我这样做 $association->members 谢谢!
  • 如果你只做$association->members,你会得到所有相关的成员,而不仅仅是活跃的一次......只是让你知道

标签: php laravel scope laravel-5 laravel-5.1


【解决方案1】:

(问题已经在cmets中回答了,但不妨写一个正确的答案)

不可能在Colletion 中使用查询范围,因为查询范围是 Eloquent 中用于向数据库查询添加约束的概念,而 Collections 只是事物(数据、对象等)的集合)。

在你的情况下,你需要做的是改变这一行:

$association->members->active()->count();

到:

$association->members()->active()->count();

之所以有效,是因为当我们将members 作为方法调用时,我们将获得一个QueryBuilder 实例,这样我们就可以在调用count 方法之前开始将作用域链接到查询。

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2019-08-10
    • 2015-06-13
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多