如何使用 knex.js 和 objection.js 在 Postgres 中查询不到 48 小时的记录?

PGT*_*PGT 3 postgresql orm node.js knex.js objection.js

我想使用created_at列查询年龄小于 48 小时的所有记录。

在 PostgreSQL 中,您可以执行以下操作:

SELECT * from "media" WHERE updated_at >= now() - '48 hour'::INTERVAL;

我们如何在 objection.js/knex.js 中编写它而不进入原始查询(或者可能使用一些原始查询来实现部分等式)?

我有工作逻辑:

const { raw } = require('objection');

return SomeModel.query()
  .andWhere(raw('updated_at >= now() - \'48 HOUR\'::INTERVAL'))
  .orderBy('updated_at')
  .first();
Run Code Online (Sandbox Code Playgroud)

但我想尽可能避免使用该raw功能,例如:

return SomeModel.query()
  .where('updated_at', '>=', 'i have no idea what to put here')
  .orderBy('updated_at')
  .first();
Run Code Online (Sandbox Code Playgroud)

一开始想到,既然updated_at是一个new Date().toISOString()我也许可以做一些类似的事情< new Date(new Date().getTime()-48*60*60*1000).toISOString()

但我不完全确定 Postgres 比较器将如何处理这个问题。

Mik*_*stö 5

const { raw } = require('objection');

SomeModel.query()
  .where('updated_at', '>=', raw(`now() - (?*'1 HOUR'::INTERVAL)`, [48]))
  .orderBy('updated_at')
  .first();
Run Code Online (Sandbox Code Playgroud)

还以小时数可以作为值绑定传递的方式编写示例。如果不必更改值,则使用常量now() - '48 HOUR'::INTERVAL也可以。