如何在 whereRaw 查询中使用绑定?
How to use bindings in a whereRaw query?
我有一个包含两列的 table,'first_name' 和 'last_name',我想加入两个 table 以便我可以搜索针对它们的查询LIKE 查询并使用 % 通配符。
当我使用字符串文字时我能够做到这一点,但是当我尝试使用位置绑定时它不起作用。我一无所获
有没有办法在没有 concat 和 whereRaw 函数的情况下连接两列?我该如何正确编写绑定?
const searchUser = (query) => {
const name = query.toLowerCase();
return knex('users')
.select('*')
.whereRaw('concat(LOWER("first_name"), \' \' , LOWER("last_name")) LIKE \'%??%\'', [name]);
};
您似乎正在尝试查询具有相同值的两个单独的列?
你可以在这里做的是一个 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));
};
我有一个包含两列的 table,'first_name' 和 'last_name',我想加入两个 table 以便我可以搜索针对它们的查询LIKE 查询并使用 % 通配符。
当我使用字符串文字时我能够做到这一点,但是当我尝试使用位置绑定时它不起作用。我一无所获
有没有办法在没有 concat 和 whereRaw 函数的情况下连接两列?我该如何正确编写绑定?
const searchUser = (query) => {
const name = query.toLowerCase();
return knex('users')
.select('*')
.whereRaw('concat(LOWER("first_name"), \' \' , LOWER("last_name")) LIKE \'%??%\'', [name]);
};
您似乎正在尝试查询具有相同值的两个单独的列?
你可以在这里做的是一个 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));
};