Laravel 5.2 Eloquent - 通过作用域访问

Laravel 5.2 Eloquent - Accessor through Scope

我有一个模型,我需要检查其值并 return 恢复不健康状态。我已经创建了一个访问器,它正在工作并且 returns true 或 false 如预期的那样。

$task->unhealthy()

访问代码

    public function getUnhealthyAttribute(){

        //Is in Active status
        if ( $this->status_id == 1 ){
            return true;
        }

        //Has overdue items
        if ( $this->items()->overdue()->count() > 0 ) {
            return true;
        }

        return false;
    }

我现在需要检索所有 "unhealthy" 任务的集合。

问题:是否可以将我的访问器与范围一起使用?什么是正确的方法?

您可以使用 collection's filter() method 仅过滤 不健康的 任务,一旦您拥有包含 所有 任务的集合:

$unhealthy_tasks = $tasks->filter(function($task, $key) {
    return $task->unhealthy; // if returns true, will be in $unhealthy_tasks
});