\ yii \ db \ Query()中的Yii2数学

时间:2019-01-18 03:34:26

标签: yii2 yii2-basic-app

我想做一些数学运算(除法,减法,加法...),并且两个或多个字段的值正在使用如下所示的Yii数据库查询。我可以这样吗?

 $data = (new \yii\db\Query())
 ->select([
  'date',
  'SUM( IF(status = "Passed", 1, 0) ) AS passed',
  'SUM( IF(status = "Failed", 1, 0) ) AS failed',
  'SUM( IF(status = "On Hold", 1, 0) ) AS onhold',
  'passed/onhold as selfsubmit',
  'COUNT(*) AS total'
 ])
 ->from('qa3d')
 ->groupBy('date')
 ->all();

1 个答案:

答案 0 :(得分:2)

首先,您不能在与MySQL相同的查询中使用别名进行算术(数学)。还有doc

但是您可以使用yii\db\Expression类进行计算,因为有了它,框架将不会尝试将表达式转义为MySQL列。

因此,基本上,您必须选择不带别名且带有Expression类的表达式。

例如:

$data = (new \yii\db\Query())
    ->select([
        'date',
        'SUM( IF(status = "Passed", 1, 0) ) AS passed',
        'SUM( IF(status = "Failed", 1, 0) ) AS failed',
        'SUM( IF(status = "On Hold", 1, 0) ) AS onhold',
        new \yii\db\Expression('SUM( IF(status = "Passed", 1, 0) ) / SUM( IF(status = "On Hold", 1, 0) ) AS selfsubmit'),
        'COUNT(*) AS total'
    ])
    ->from('qa3d')
    ->groupBy('date')
    ->all();