如何组合/连接 2 列,然后使用 Knex 查询生成器对组合值进行模糊搜索
模糊搜索正在处理accounts.first_name
&accounts.last_name
搜索(search_cols
数组中的前 2 个项目
在大多数情况下,连接似乎不尊重列名如何传递到查询中。
const search_cols = [
// other columns
"accounts.first_name",
"accounts.last_name",
// ❌ "'accounts.first_name' || ' ' || 'accounts.last_name'",
// ERROR missing FROM-clause entry for table "first_name' || ' ' || 'accounts"
// ❌ "first_name || ' ' || last_name",
// ERROR column "first_name || ' ' || last_name" does not exist
// ❌ "CONCAT(accounts.first_name, accounts.last_name)",
// missing FROM-clause entry for table "first_name, accounts"
// ❌ "CONCAT(accounts.first_name, ' ' , accounts.last_name)",
// missing FROM-clause entry for table "first_name, ' ' , accounts"
// ❌ "CONCAT('accounts.first_name', ' ' , 'accounts.last_name')"
// missing FROM-clause entry for table "first_name', ' ' , 'accounts"
// ❌ `CONCAT("accounts"."first_name", ' ', "accounts"."last_name")`
// missing FROM-clause entry for table ""first_name", ' ', "accounts""
]
const pages = await Page.query()
.join("accounts", "accounts.id", "account_id")
.select([
// other columns
"accounts.first_name",
"accounts.last_name",
])
.where((builder) => {
// SEARCH
if (req.query.search_term) {
for (const [idx, col] of search_cols.entries()) {
console.log('THE CURRENT COLUMN', col)
if (idx === 0) {
builder.where(col, "ilike", `%${req.query.search_term}%`)
} else {
builder.orWhere(col, "ilike", `%${req.query.search_term}%`)
}
}
}
}