简体   繁体   English

如何使用 Postges 和 Knex.js 查询特定月份的日期字段

[英]How to query a date field for a specific month with Postges and Knex.js

Im setting up a new date query using Knex.js and Postgres.我使用 Knex.js 和 Postgres 设置了一个新的日期查询。 I need to return all the rows for a specific month from the table.我需要从表中返回特定月份的所有行。

This is for a simple app API.这是一个简单的应用程序 API。 Ive managed to return all the fields from the table that I want but don't know how to query the date field for the specific month.我设法从我想要的表中返回所有字段,但不知道如何查询特定月份的日期字段。 Im using Knex.js as my query builder and have the following:我使用 Knex.js 作为我的查询构建器并具有以下内容:

db('table').select() 
.where('Month(date)', '=', 0  ); //this field where I am lost, 

the sql I think will do the job is: EXTRACT(MONTH FROM dateColumn::date) = 1我认为可以完成这项工作的 sql 是: EXTRACT(MONTH FROM dateColumn::date) = 1

I get an error at the moment.我现在收到一个错误。 But I am expecting to query to return all the date fields that are in the month of January.但我希望查询返回一月份的所有日期字段。 I know that I could use the .whereRaw() field but Im not 100% sure how to use this either as the documentation does not provide any use cases for date fields.我知道我可以使用.whereRaw()字段,但我不是 100% 确定如何使用它,因为文档没有提供任何日期字段的用例。

For reference the column date that I want to query is of format date作为参考,我要查询的列date是格式date

I managed to get this to work by using the .whereRaw() API of knex.我设法通过使用.whereRaw() API 使其工作。

.andWhereRaw(`EXTRACT(MONTH FROM dateColumn::date) = ?`, [monthVariable])

Im not totally sure why, but it only worked with the ::date suffix to my dateColumn .我不完全确定为什么,但它只适用于我的dateColumn::date后缀。 This will cast my dateColumn to postgres dateType.这会将我的 dateColumn 转换为 postgres dateType。 The confusing part is that the dateColumn was already of type date .令人困惑的部分是dateColumn已经是date类型。

也许这个:

db('table').where(db.raw('EXTRACT(MONTH FROM ??::date)', ['dateColumn']), 0)

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

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