简体   繁体   中英

How to use postgres ::date with knex.js

I have a column of type timestamp . I need to select all records by given date. In sql it's something like:

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

because knex place quotes wrong.

Is there any way to perform such query? Or I should use whereRaw ?

For dialect specific functionality like this you often need to use knex.raw . In this case you can the shorthand, 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) . You can try to find this cast in your framework.

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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