在下面的代码中,我加入了两个表并搜索了一个专有名称:
const homesWithUsers = knex('homes')
.join('users', 'homes.id', 'users.home_id')
.whereRaw(
`LOWER("homes.name") LIKE ?`,
'%' + payload.home_name.toLowerCase() + '%'
)
//Stringified
select * from "homes" inner join "users" on "homes"."id" = "users"."home_id" where LOWER("homes.name") LIKE '%george%'
我需要使用 whereRaw
,因为数据库列和搜索词是大写不确定的专有名称。 (存储以全部大写表示的专有名称的额外列不是一种选择。)但是,此查询失败并显示:错误:列“homes.name”不存在
。如果我删除 homes.
查询是不明确的(error: column reference "name"is ambiguous
),因为 user
和 home
表有 name
列。
如果我执行一个简单的 where
语句,查询就会成功
const homesWithUsers = knex('funeral_homes')
.join('users', 'homes.id', 'users.home_id')
.where({ 'homes.name': payload.home_name })
.select('*');
唯一的问题是,这将因我希望从与数据库交互的用户那里获得的有效负载值而失败。
对于如何在联接表上成功执行 whereRaw
有什么建议吗?
最佳答案
在将列标识符传递给 raw 时,您需要使用标识符替换语法 ??
,这需要正确引用。像这样:
const homesWithUsers = knex('homes')
.join('users', 'homes.id', 'users.home_id')
.whereRaw(
`LOWER(??) LIKE ?`, ["homes.name", '%' + payload.home_name.toLowerCase() + '%']
)
关于javascript - knexjs 和 postgres : whereRaw within a join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461746/