Laravel postgres current_timestamp

时间:2016-10-16 02:49:07

标签: postgresql laravel-5 timestamp

您好我当前的时间戳查询有问题我正在使用laravel和postgres。我的查询是这样的

 $min_max_avg = DB::table('token_queue')                             
    ->join('token', 'token.id', '=', 'token_queue.token_id')                             
    ->select(DB::raw('MIN(serving_end_time - serving_start_time) AS min_total_serving_time'))                                                       
    ->whereBetween('token.generated_time',[DB::raw("date_trunc('hour', CURRENT_TIMESTAMP)"), 
                                           DB::raw("date_trunc('hour', CURRENT_TIMESTAMP + interval '1 hour')")])
    ->first();

生成像这样的SQL

select 
MIN(serving_end_time - serving_start_time) AS min_total_serving_time
from "token_queue" inner join "token" on "token"."id" = "token_queue"."token_id" 
where "token"."generated_time" between date_trunc('hour', CURRENT_TIMESTAMP) and date_trunc('hour', CURRENT_TIMESTAMP + interval '1 hour') 

所以当我在pgAdmin中运行这个sql时,它工作正常,但它在给我错误的方面做了很多事 日期时间格式无效:7错误:类型为timestamp的输入语法无效:“date_trunc('hour',CURRENT_TIMESTAMP)”

我的桌子就像这样

令牌

id       | generated_time
196618   | 2016-10-15 01:02:48.963
196619   | 2016-10-15 01:02:50.569
196620   | 2016-10-15 01:03:12.931
196621   | 2016-10-15 02:03:17.037
196622   | 2016-10-15 02:22:55.782
196623   | 2016-10-15 02:24:57.477
196624   | 2016-10-15 03:23:00

token_queue

id | serving_start_time      | serving_end_time        | token_id
1  | 2016-10-15 01:02:48.963 | 2016-10-15 01:03:02.69  | 196618

感谢您的任何建议。

1 个答案:

答案 0 :(得分:2)

我对Laravel了解不多,但是一些谷歌搜索给了我一个坚定的印象,即在调用whereBetween时,在RHS上不会尊重DB :: Raw。

尝试使用whereRaw()在原始SQL中添加所需的where子句。

->whereRaw("token.generated_time between date_trunc('hour', CURRENT_TIMESTAMP) and date_trunc('hour', CURRENT_TIMESTAMP + interval '1 hour')")