简体   繁体   English

如何使用postgres :: date和knex.js

[英]How to use postgres ::date with knex.js

I have a column of type timestamp . 我有一个类型为timestamp的列。 I need to select all records by given date. 我需要按给定日期选择所有记录。 In sql it's something like: 在sql中它是这样的:

select * from "table" where "date"::date = '2015-08-22';

I tried following: 我试过以下:

db('table').select().where('date::date', '=', date);

But this throws error 但这会引发错误

error: select * from "table" where "date::date" = $1 - column "date::date" does not exist 错误:从“table”中选择*,其中“date :: date”= $ 1 - 列“date :: date”不存在

because knex place quotes wrong. 因为knex的地方引用错了。

Is there any way to perform such query? 有没有办法执行这样的查询? Or I should use whereRaw ? 或者我应该使用whereRaw

For dialect specific functionality like this you often need to use knex.raw . 对于像这样的方言特定功能,您经常需要使用knex.raw In this case you can the shorthand, whereRaw . 在这种情况下你可以用速记, whereRaw

db('table').select().where(knex.raw('??::date = ?', ['date', date]));
db('table').select().whereRaw('??::date = ?', ['date', date]);

::someType is a postgres way of using standard cast(something as sometype) . ::someType是一种使用标准::someType的postgres方式cast(something as sometype) You can try to find this cast in your framework. 您可以尝试在框架中找到此cast

Other option is to use date_trunc('day',date) = to_date('2015-08-22', 'YYYY-MM-DD') or date_trunc('day',date) = '2015-08-22' 其他选项是使用date_trunc('day',date) = to_date('2015-08-22', 'YYYY-MM-DD')date_trunc('day',date) = '2015-08-22'

You got the type casting idea reversed, hence the issue: Data casting is to be applied to values, not to column names. 你反映了类型转换的想法,因此问题是:数据转换应用于值,而不是列名。

ie change to this: 即改为:

select * from "table" where "date" = '2015-08-22'::date;

And you can still use a date/time function on column date , if you need to extract a part from it, or to match to another type. 如果您需要从中提取零件,或者匹配另一种类型,您仍然可以在列date使用日期/时间功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM