有没有办法在 AdonisJS 4.1.0 中进行条件查询?

is there a way to do conditional query in AdonisJS 4.1.0?

我正在关注 AdonisJs 的查询生成器:https://adonisjs.com/docs/4.1/query-builder#_introduction

我正在尝试做一些类似于在他们的 'Conditional Queries' 副标题下发布的示例:

const query = Database.table('users')
if (username) {
  query.where('username', username)
}

但是,这会在我的后端发送一个错误。

有没有办法做有条件的where查询?在某些情况下,我需要有 where 子句,而在其他基于布尔值的情况下,我需要所有数据,因此不需要 where。

我注意到 'query' 变量(在上面的示例中)只有在链接到数据库 class 时才可链接。当我将其保存为变量时,它会抛出错误(即 query.where(...) 抛出错误)。

我目前的解决方案是为 3 个布尔条件设置 9 种可能性,并且每个查询都将从数据库 class 创建。不过我可能很快就会有超过 3 个条件。

有没有办法进行条件查询?

P.S:我知道我可以在一个 where 子句中包含多个字段,尽管这与我的问题无关。 IE。 .where({ field1: true, field2: false})

没关系,

const query = Database.table('users')
if (username) {
  query.where('username', username)
}

有效。我在不应该的时候在数据库上使用了 await。