【问题标题】:Use operators 'like` or 'greater than' in Knex query with object syntax在具有对象语法的 Knex 查询中使用运算符“like”或“大于”
【发布时间】:2016-07-03 11:29:50
【问题描述】:

我正在使用 JSON 对象来构建这样的 Knex 查询:

{where: {id: '5'}

如何将相同的查询格式(对象语法)与 likegreater than 等运算符一起使用?

【问题讨论】:

  • 为像我这样正在寻找一种在没有对象语法的情况下使用大于/小于使用 Bookshelf 或 Knex 的方法的人留下评论:knex('users').where('votes', '>', 100)BookshelfModel.query('where', 'votes', '>', 100) 应该可以工作。

标签: bookshelf.js knex.js


【解决方案1】:

您可以使用where/andWhere。下面的代码显示了仅当 user_id = userIdbook_reference = bookName 并且 result 时才会发生的更新。

knex('user_books')
    .where({
      user_id: userId,
      book_reference: bookName
    })
    .andWhere('result', '<', res)
    .update({
      'updated_at': bookshelf.knex.raw('CURRENT_TIMESTAMP'),
      'text_done': true,
    })

【讨论】:

    【解决方案2】:

    我认为这是不可能的。看the relevant source code of the query builder,是这样的:

    _objectWhere(obj) {
      const boolVal = this._bool();
      const notVal = this._not() ? 'Not' : '';
      for (const key in obj) {
        this[boolVal + 'Where' + notVal](key, obj[key]);
      }
      return this;
    }
    

    它基本上只用两个参数调用适当的Where 函数(因此没有运算符,这意味着=

    【讨论】:

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