php - groupBy() 方法给出空结果 Yii2

标签 php mysql yii2

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

\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

最佳答案

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

关于php - groupBy() 方法给出空结果 Yii2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50278333/

相关文章:

php - CentOS 7.x 上 Laravel : PHP 7. x 的 Docker 容器

MYSQL: 无法添加外键约束

php - Yii2 GridView无法设置列宽

javascript - 在 NodeJS 上分配变量来查询 mysql

mysql - 优化慢查询

php - Yii2 - 获取未知属性:yii\console\Application::user

Yii2:如何在 yii2 中添加 textarea

php - 如何使用 PHP imgttftext() 函数将 unicode 单词正确写入图像

PHP 中的 JAVA DES

php - 使用 dirname 两次或三次向上移动两个或三个文件夹