【问题标题】:Laravel 5.2 Eloquent - Accessor through ScopeLaravel 5.2 Eloquent - 通过范围访问器
【发布时间】:2016-08-14 23:53:38
【问题描述】:

我有一个模型,我需要检查它的值并返回一个不健康的状态。我创建了一个访问器,它正在工作并按预期返回 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;
    }

我现在需要检索所有“不健康”任务的集合。

问题:是否可以通过范围利用我的访问器?什么是正确的方法?

【问题讨论】:

    标签: laravel scope eloquent accessor


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 1970-01-01
      • 2016-12-20
      • 2018-12-05
      • 2017-10-30
      • 2016-09-24
      • 2016-11-04
      • 2011-06-29
      • 2011-08-19
      相关资源
      最近更新 更多