【问题标题】:knexjs and postgres: whereRaw within a joinknexjs 和 postgres:连接中的 whereRaw
【发布时间】:2018-12-29 21:35:12
【问题描述】:

在以下代码中,我将加入两个表并搜索正确的名称:

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,因为数据库列和搜索词是大小写不确定的专有名称。 (存储一个额外的以全大写形式表示的专有名称的列不是一种选择。)但是,此查询失败并显示:error: column "homes.name" does not exist。如果我删除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 的任何建议?

【问题讨论】:

    标签: javascript database postgresql join knex.js


    【解决方案1】:

    在将列标识符传递给 raw 时,您需要使用标识符替换语法??,这需要正确引用。像这样:

    const homesWithUsers = knex('homes')
      .join('users', 'homes.id', 'users.home_id')
      .whereRaw(
         `LOWER(??) LIKE ?`, ["homes.name", '%' + payload.home_name.toLowerCase() + '%']
       )
    

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 2017-05-26
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 2014-07-07
      相关资源
      最近更新 更多