【问题标题】:Cakephp 3 multiple condition in containCakephp 3中包含的多个条件
【发布时间】:2017-08-30 12:04:29
【问题描述】:

我想通过相关的 Jobstasks 获得我的 Jobs,但我想从 Jobstasks 中计算 total1 - 工作中的所有任务(效果很好)和(评论,当然不工作)total2 - 计算完成的任务。有什么想法吗?

$jobs = $this->Jobs->find('all')
            ->where(['Jobs.user_id' => $user_id])
            ->andWhere(['Jobs.start >' => new \DateTime('+6 days')])
            ->contain(['Jobgroups', 
                'Jobstasks' => function($q){
                    $q->select([
                        'JobsTasks.job_id',
                        'JobsTasks.finished',
                        'total1' => $q->func()->count('JobsTasks.job_id'), 
                        //'total2' => $q->func()->where(['JobsTasks.finished' => true])->count()
                    ])->group(['JobsTasks.id']);
                    return $q;
                }

            ])
            ->order(['Jobs.start' => 'ASC']);

【问题讨论】:

    标签: orm count associations cakephp-3.0 contain


    【解决方案1】:

    我猜你可以简单地对完成的列求和,因为完成的任务为 1,否则为 0

    'total1' => $q->func()->sum('JobsTasks.finished')
    

    这适用于布尔值。如果您有更复杂的条件,我会创建一个计算字段来评估您的条件,而不是 WHERE 子句

    类似

    'total2' => "SUM(IF(JobsTasks.finished = true, 1, 0))" 
    

    【讨论】:

      【解决方案2】:

      感谢您,Arilia,您的 total2 效果很好 :) 没有必要更改 total1。下面是解决方案。而且我必须更改分组以获得正确的数据输出。

      $jobs = $this->Jobs->find('all')
                  ->where(['Jobs.user_id' => $user_id])
                  ->andWhere(['Jobs.start >' => new \DateTime('+6 days')])
                  ->contain(['Jobgroups', 
                      'Jobstasks' => function($q){
                          $q->select([
                              'JobsTasks.job_id',
                              'total1' => $q->func()->count('JobsTasks.finished'), 
                              'total2' => "SUM(IF(JobsTasks.finished = 1, 1, 0))" 
                          ])->group(['JobsTasks.job_id']);
                          return $q;
                      }
                  ])
                  ->order(['Jobs.start' => 'ASC']);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-18
        • 2015-04-03
        • 2013-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多