Knex 查询生成器`where` 和`andWhere` 有条件地添加区别?

Knex query builder `where` and `andWhere` difference added conditionally?

我需要向 knex 查询生成器添加多个 where 语句,并对 whereandWhere 的区别感到困惑。

const qb = this.query();

if (userId) {
  qb.where('user_id', userId);
}

if (bookId) {
  // what is the difference?
  // qb.where('book_id', bookId);
  qb.andWhere('book_id', bookId);
}
  1. 如果我在第二个条件下使用where,它会重写user_id条件吗?或者它只会为同一个密钥重写它?

根据我的经验,添加第二个 .where() 子句会自动使用 'AND' 连接第一个 .where(),因此实际上与使用 .andWhere() 相同。但这没有记录,因此您可能不想依赖该行为。

顺便说一句,我经常在验证代码时将以下子句添加到查询执行中,以允许我查看生成的 SQL.

/* your code above */
.on('query', function(data) {
    // outputs the SQL query you generated & runtime data bindings.
    console.log(data);
})