[英]How to query for records less than 48 hours in Postgres using knex.js and objection.js?
I'd like to query for all records less than 48 hours of age using a created_at
column. 我想使用created_at
列查询小于48小时的所有记录。
In PostgreSQL you can do something like: 在PostgreSQL中,您可以执行以下操作:
SELECT * from "media" WHERE updated_at >= now() - '48 hour'::INTERVAL;
How do we write this in objection.js/knex.js without going into raw query (or maybe using some raw for part of the equality)? 我们如何在objection.js / knex.js中写这个而不进入原始查询(或者可能使用一些原始的部分相等)?
I have working logic: 我有工作逻辑:
const { raw } = require('objection');
return SomeModel.query()
.andWhere(raw('updated_at >= now() - \'48 HOUR\'::INTERVAL'))
.orderBy('updated_at')
.first();
But I would like to avoid using the raw
function if possible so something like: 但我想尽可能避免使用raw
函数,例如:
return SomeModel.query()
.where('updated_at', '>=', 'i have no idea what to put here')
.orderBy('updated_at')
.first();
Upon first thought, since updated_at
is an new Date().toISOString()
I may be able to do something along the lines of < new Date(new Date().getTime()-48*60*60*1000).toISOString()
首先想到的是,因为updated_at
是一个new Date().toISOString()
我可以做一些基于< new Date(new Date().getTime()-48*60*60*1000).toISOString()
But I'm not entirely sure how the Postgres comparator is going to handle this. 但我不完全确定Postgres比较器将如何处理这个问题。
const { raw } = require('objection');
SomeModel.query()
.where('updated_at', '>=', raw(`now() - (?*'1 HOUR'::INTERVAL)`, [48]))
.orderBy('updated_at')
.first();
Also wrote example in a way that number of hour can be passed as value binding. 还以一种小时数可以作为值绑定传递的方式编写示例。 If value does not have to be changed then using constant now() - '48 HOUR'::INTERVAL
is fine too. 如果不必更改值,则使用常量now() - '48 HOUR'::INTERVAL
也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.