【问题标题】:Different result beween eloquent query and the same associated SQL query (got with toSql() method ) with Laravel使用 Laravel 的 eloquent 查询和相同的关联 SQL 查询(使用 toSql() 方法获得)不同的结果
【发布时间】:2020-11-19 03:13:47
【问题描述】:

我在 Laravel Eloquent 中有这个查询:

$measures = Measure::groupBy('time')
        ->selectRaw('time, sum("delta") as sum_delta, sum("redistributed") as sum_redistr') 
        ->where('operation_id', 'ACC0000001') 
        ->where('time', '>', '2020-05-09 00:00') 
        ->where('time', '<', '2020-05-10 00:00') 
        ->where('source', 'source1') 
        ->where('conso_prod', 'Conso')
        ->get()

当我使用toSql() 函数进行调试,然后将其粘贴到 pgAdmin 中时,我得到了正确的结果。

select time, sum("delta") as sum_delta, sum("redistributed") as sum_redistr from "measures" 
where "operation_id" = 'ACC0000001'
and "time" > '2020-05-09' and "time" < '2020-05-10' and "source" = 'source1' and "conso_prod" = 'Conso' group by "time"

我每 30m 有一个结果,这是正确的。

但是当我使用 eloquent 时,我的行数相同,但所有 time 字段都相同:

"2020-05-09 00:00"

而不是递增。

我不明白为什么?我使用带有 TimescaleDB 扩展的 PostgreSQL。

【问题讨论】:

  • 快速提问; timemeasures 表上的列还是 PGSql 关键字?有时,当您使用 selectRaw() 时,您需要在列周围使用波浪号(如时间)以避免这种情况。话虽如此,那是针对 MySQL 的;我对 PGSql 的工作不多,所以我不能说这是否是个问题。
  • “时间”列是保存时间值还是日期时间值?
  • time 是具有时间戳值的列。它也是一个特殊的列,因为 TimescaleDB 是一个时间序列数据库。

标签: laravel postgresql eloquent timescaledb


【解决方案1】:

在我的模型中,我将时间分配给 date 而不是 datetime

protected $casts = [
    'time' => 'date'
];

我改成了:

protected $casts = [
    'time' => 'datetime'
];

它奏效了。

如果有人像我一样失败,我会放在那里!无论如何感谢您的帮助

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 2021-12-17
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2016-02-08
    • 2019-10-22
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多