【问题标题】:How to use bindings in a whereRaw query?如何在 whereRaw 查询中使用绑定?
【发布时间】:2022-01-09 22:10:22
【问题描述】:

我有一个包含“first_name”和“last_name”两列的表,我想加入这两个表,以便可以使用 LIKE 查询并使用 % 通配符搜索查询。

当我使用字符串文字时,我能够做到这一点,但是当我尝试使用位置绑定时它不起作用。我一无所有。

有没有办法在没有 concat 和 whereRaw 函数的情况下连接两列?以及如何正确编写绑定?

const searchUser = (query) => {
  const name = query.toLowerCase();
  return knex('users')
    .select('*')
    .whereRaw('concat(LOWER("first_name"), \' \' , LOWER("last_name")) LIKE \'%??%\'', [name]);
};

【问题讨论】:

    标签: postgresql knex.js


    【解决方案1】:

    您似乎正在尝试查询具有相同值的两个单独的列?

    您可以在这里做的是一个orWhere 链,它将多个 where 语句链接在一起,如果只有一个为真,则匹配。

    例如:

    const searchUser = (query) => {
      return knex('users')
        .select('*')
        .where(knex.raw('first_name ILIKE ?', `%${query}%`))
        .orWhere(knex.raw('last_name ILIKE ?', `%${query}%`));
    };
    

    这也使用了“ILIKE”,它可以让您获得与使用 LOWER 函数实现的相同的不区分大小写的匹配。

    您还可以使用命名绑定而不是位置绑定来查找值。这看起来像这样:

    const searchUser = (query) => {
      const bindings = { query: `%${query}%` };
      return knex('users')
        .select('*')
        .where(knex.raw('first_name ILIKE :query', bindings))
        .orWhere(knex.raw('last_name ILIKE :query', bindings));
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-03
      • 2017-04-12
      • 2020-02-08
      • 2019-09-01
      • 2017-03-03
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多