代码之家  ›  专栏  ›  技术社区  ›  mchlstckl

在查询生成器中否定现有的KNEX WHERE子句

  •  0
  • mchlstckl  · 技术社区  · 7 年前

    我有一个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'))`
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Mikael Lepistö    7 年前

    当前不支持的 knex .

    将来,有了这个特性,可以通过将where子句与查询生成器的其余部分分开存储来实现这一点 https://github.com/tgriesser/knex/issues/1893

    所以现在你需要改变你的代码 捏合 在知道where子句是否应该被否定之前,不要实际构建它。

        2
  •  0
  •   Vandré A. Schaedler    7 年前

    如果我知道您想要什么,可以使用修改:

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

    只有在negateSearch为true时,它才会添加“whereNot”条件。