My Association model looks like this (irrelevant code redacted):

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

Now, I'm aware there's a difference between a Query and a Collection. But what I'm basically asking is if there's some kind of similar scope for collections. Of course, the optimal solution would be to not have to write TWO active methods, but use one for both purposes.

推荐答案

(问题已在 comments 中得到回答,但不妨写一个恰当的答案)

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

In your case, what you need to do is to change this line:

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

to:

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

This works because when we call members as a method, we are getting a QueryBuilder instance, and with that we can start chaining scopes to the query before calling the count method.

Laravel相关问答推荐

AJAX响应中未定义的全名

使用 Laravel 10 在 Blade 中添加成功消息

函数接受 Laravel 集合对象,尽管只允许使用字符串

仅针对字母的 laravel 验证规则

Laravel 在维护模式下显示自定义消息

查询 Laravel Select WhereIn 数组

Laravel 4 的 Cron 作业(job)

你如何在自定义 Laravel Nova 工具中使用确认对话?

Laravel vagrant up 不工作 - Errno::EADDRNOTAVAIL

Laravel 判断约束违规

判断输入是否来自控制台

Laravel 5 Carbon 全局语言环境

使用哪个 Auth::check() 或 Auth::user() - Laravel 5.1?

日期时间格式无效:1366 字符串值不正确

Laravel 数据库模式中的 MediumBlob

Laravel - artisan不工作

如何在脚本文件中使用 Laravel Blade?

Laravel:如何在 PhpUnit 上启用堆栈跟踪错误

以编程方式而不是从 CLI 运行 Laravel 5 seeder

连接到 tcp://smtp.mail.yahoo.com:465 超时