如何在 knex.js 中使用 postgres ::date

How to use postgres ::date with knex.js

我有一个 timestamp 类型的列。我需要 select 给定日期的所有记录。在 sql 中是这样的:

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

我试过以下方法:

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

但这会引发错误

error: select * from "table" where "date::date" = - column "date::date" does not exist

因为knex地方引号错了

有什么方法可以执行这样的查询吗?或者我应该使用 whereRaw?

::someType 是一种使用标准 cast(something as sometype) 的 postgres 方式。你可以尝试在你的框架中找到这个cast

其他选项是使用 date_trunc('day',date) = to_date('2015-08-22', 'YYYY-MM-DD')date_trunc('day',date) = '2015-08-22'

你颠倒了类型转换的想法,因此出现了问题:数据转换应用于值,而不是列名。

即更改为:

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

如果您需要从中提取一部分,或者匹配另一种类型,您仍然可以在列 date 上使用 date/time 函数。

对于像这样的方言特定功能,您通常需要使用 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]);