groupby()方法给出空结果yii2

wydwbb8l  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(238)

尝试使用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;

原始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版本2.0.15.1

5hcedyr0

5hcedyr01#

默认情况下 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;

相关问题