首页 > 解决方案 > KnexJS Postgres:为原始查询添加额外的双引号

问题描述

考虑下面的代码:

const items = await Item.query().where(
      "type",
      "like",
      raw("'??'", [`%${term}%`])
);

上面的代码我没有收到任何错误,但是数据库返回了一个空的结果集。创建的 SQL 查询如下:

select "items".* from "items" where type LIKE '%"mobiles"%'

请看上面SQL中的like mobiles'%"mobiles"%' ""被视为值的一部分并返回一个空的结果集。

""在上面的查询中如何避免?

编辑:请注意,我使用的 ObjectionJS 也使用了 Knex。

标签: postgresqlknex.js

解决方案


??应该用于列名。

我给你2个建议,

  1. 完全不使用查询raw
const items = await Item.query().where('type', 'like', `%${term}%`);
  1. 使用单?
const items = await Item.query().where('type', 'like', raw("'?'", [`%${term}%`]));

推荐阅读