groupBy()方法给出空结果Yii2

时间:2018-05-10 17:26:08

标签: php mysql yii2

尝试使用groupBy()方法创建请求,但yii2返回空结果。 这是我的行动:

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$data = MachineLog::find()
            ->select(['sum(value)', 'max(datetime)'])
            ->where([ '<', 'datetime', $end->format('Y-m-d G:i:s') ])
            ->andWhere([ '>', 'datetime', $start->format('Y-m-d G:i:s') ])
            ->andWhere([ 'type' => $type, 'machine_id' => $machineId[0] ])
            ->groupBy(["UNIX_TIMESTAMP(datetime) DIV $diffInSeconds"])
            ->all();
return $data;

Raw SQL提供足够的结果,请求与yii2生成的请求相同。

mysql> SELECT sum(value), max(datetime) FROM `machine_log` WHERE (`datetime` < '2018-05-10 17:00:00') AND (`datetime` > '2018-05-10 16:30:00') AND ((`type`='1') AND (`machine_id`='4')) GROUP BY UNIX_TIMESTAMP(datetime) DIV 180;
+------------+---------------------+
| sum(value) | max(datetime)       |
+------------+---------------------+
|       NULL | 2018-05-10 16:32:52 |
|       NULL | 2018-05-10 16:35:52 |
|       NULL | 2018-05-10 16:38:52 |
|          2 | 2018-05-10 16:41:59 |
|         36 | 2018-05-10 16:44:59 |
|         36 | 2018-05-10 16:47:59 |
|         36 | 2018-05-10 16:50:59 |
|         36 | 2018-05-10 16:53:59 |
|         35 | 2018-05-10 16:56:59 |
|         37 | 2018-05-10 16:59:59 |
+------------+---------------------+
    10 rows in set (0.06 sec)

Yii Version 2.0.15.1

1 个答案:

答案 0 :(得分:1)

默认情况下all()返回模型数组。如果您使用select()中的自定义列构建此类自定义查询,则需要使用asArray()强制将行返回为数组而不是ActiveRecord对象(无法通过查询创建)结果)。

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$data = MachineLog::find()
        ->select(['sum(value)', 'max(datetime)'])
        ->where([ '<', 'datetime', $end->format('Y-m-d G:i:s') ])
        ->andWhere([ '>', 'datetime', $start->format('Y-m-d G:i:s') ])
        ->andWhere([ 'type' => $type, 'machine_id' => $machineId[0] ])
        ->groupBy(["UNIX_TIMESTAMP(datetime) DIV $diffInSeconds"])
        ->asArray()
        ->all();

return $data;