gpt4 book ai didi

javascript - knexjs 和 postgres : whereRaw within a join

转载 作者:行者123 更新时间:2023-11-29 13:43:52 33 4
gpt4 key购买 nike

在下面的代码中,我加入了两个表并搜索了一个专有名称:

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),因为 userhome 表有 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com