【问题标题】:In postgresql, how to use 'where' in Knex.raw as the data to 'where' is coming from a subquery?在 postgresql 中,如何在 Knex.raw 中使用“where”作为“where”的数据来自子查询?
【发布时间】:2020-02-08 19:03:44
【问题描述】:

这是我的代码 我想使用 regexp_replace 所以我尝试使用 Knex.raw 但我发现很难使用 where 子句

  async function test () {
  let usernameData = {
      oldUserName: 'MobileOpsteam',
      newUserName: 'cool'
  }
  const oldUserNameRegex = `@${usernameData.oldUserName}(?![a-zA-Z0-9])`

  const newUserName = `@${usernameData.newUserName}`

  let subQuery = await knex.select('id').from('user_notification').where('title', 'like', `%${usernameData.oldUserName}%`)
  let result = await knex.raw((`update user_notification set title = regexp_replace(title, ${oldUserNameRegex}, ${newUserName}, 'g')`).whereIn('id', subQuery))
// let result = await knex.raw(`update user_notification set title = regexp_replace(title, ${oldUserNameRegex}, ${newUserName}, 'g') where id in ${subQuery}`)
  console.log(result)
}

【问题讨论】:

    标签: node.js postgresql knex.js


    【解决方案1】:

    这样的事情应该可以工作:

      // subquery builder is not awaited, since query should not be executed separately
      let subQuery = knex.select('id')
        .from('user_notification').where('title', 'like', `%${usernameData.oldUserName}%`)
    
      let result = await knex('user_notification')
          .update({
              title: knex.raw(
                         `regexp_replace(??, ${oldUserNameRegex}, ${newUserName}, 'g')`, 
                          ['title'])
          }).whereIn('id', subQuery)
    

    基本上knex.raw() 不能附加任何额外的.where(...) 等,因为原始构建器没有关于它包含的SQL 的语法元素的任何信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多