【问题标题】:Negate existing knex where clause in query builder否定查询生成器中现有的 knex where 子句
【发布时间】:2018-11-16 15:59:32
【问题描述】:

我有一个 knex QueryBuilder 对象qb,其中包含许多where 子句。我希望能够将整个 where 子句包装在一个 not 语句中,从而有效地否定整个 where 子句。

例子:

const qb = knex.queryBuilder();
qb.whereIn('name', ['alice', 'bob']);

// ... in some other part of the file ...

// Example of what I would like to do, effectively negate the above query if
// some condition is met.
if (negateSearch) {
    const outerQb = knex.queryBuilder();
    outerQb.whereNot(qb);
    // execute outerQb
} else {
    // execute qb
}

这应该会产生一个看起来像

的查询
where not (name in ('alice', 'bob'))`

【问题讨论】:

    标签: knex.js


    【解决方案1】:

    knex 目前不支持该功能。

    未来,有了这个功能,人们可能会通过将 where 子句与查询构建器的其余部分分开存储来实现这一点 https://github.com/tgriesser/knex/issues/1893

    因此,现在您需要更改使用 knex 的代码,以便在您知道是否应该否定它之前不实际构建 where 子句。

    【讨论】:

      【解决方案2】:

      如果我明白你想要什么,你可以使用 modify:

      knex('table')
      .whereIn('name', ['alice', 'bob']);
      .modify((query) => {
        if (negateSearch) {
          query.whereNot('yourcondition')
        }
      })
      .orderBy('anyColumn', 'desc')
      

      仅当 negateSearch 为真时,它才会添加 'whereNot' 条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-03
        • 2016-10-09
        • 2013-09-16
        相关资源
        最近更新 更多