📜  whereIn knex (1)

📅  最后修改于: 2023-12-03 15:21:08.753000             🧑  作者: Mango

使用 Knex 的 WhereIn

Knex 是一个流行的 JavaScript 查询构建器,它可以用于构建和执行 SQL 查询。其中一个重要功能是使用 whereIn 条件。

使用场景

whereIn 主要是用于过滤查询结果集中包含在指定列表中的记录。例如,如果有一个 products 表,其中包含了产品的相关信息,我们可以使用 whereIn 查找具有指定 id 的产品:

knex('products')
  .whereIn('id', [1, 2, 3])
  .then((rows) => {
    console.log(rows);
  })
  .catch((error) => {
    console.error(error);
  });

这将返回一个包含 id 为 1、2 或 3 的产品记录列表。

嵌套条件

whereIn 还可以与其他条件组合使用。例如,假设有一个 users 表,其中包含用户的相关信息,我们可以使用 whereIn 找出在指定位置的活跃用户:

knex('users')
  .where('status', 'active')
  .whereIn('location', function() { 
    this.select('id')
        .from('locations')
        .where('name', 'like', '%California%');
  })
  .then((rows) => {
    console.log(rows);
  })
  .catch((error) => {
    console.error(error);
  });

这将返回在具有名称类似于“加利福尼亚”的位置处活动的用户记录。

结论

whereIn 是 Knex 查询构建器的一个强大功能,可以用于过滤查询结果集中对应于指定列表的记录。它还可以与其他条件组合使用以实现更复杂的查询。