DexieJS(indexedDB)链多个.where子句

DexieJS (indexedDB) chain multiple .where clauses

本文关键字:where 子句 indexedDB DexieJS      更新时间:2023-09-26

我正在使用DexieJS从IndexedDB获取数据。我已经对 v. 1.1.0 和 1.2.0 进行了以下测试。

它非常适合简单的查询,但不幸的是,我无法链接多个 where 子句。

首先,我试过这个

var collection = db[table];
collection = collection.where('Field').equals("1");
return collection.count();

这奏效了。然后,我需要添加一个 where 子句,但前提是设置了给定值:

var collection = db[table];
collection = collection.where('Field').equals("1");
if(value) collection = collection.where('Field2').above(value);
return collection.count();

这个失败了。出于测试目的,我还尝试了:

var collection = db[table];
collection = collection.where('Field').equals("1")
.and('Field2').above(value);
return collection.count();
var collection = db[table];
collection = collection.where('Field').equals("1")
.and().where('Field2').above(value);
return collection.count();
var collection = db[table];
collection = collection.where('Field').equals("1")
.where('Field2').above(value);
return collection.count();

这些都不起作用。我开始认为这根本不可能,但既然方法and()存在,那么一定有办法!

PS这有效:

var collection = db[table];
collection = collection.where('Field2').above(value);
return collection.count();

DexieJS的AND运算符被实现为过滤器函数或复合索引。实现查询的简单方法是使用 filter 方法,例如;

var collection = db[table];
collection = collection
    .where('Field').equals("1")
      .and(function(item) { return item.Field2 > value });
return collection.count();

这意味着第一个过滤器将针对 IndexedDB 运行,并且附加条件将由 DexieJS 针对找到的每个项目运行,这可能足以满足您的需求,也可能不够好。

至于如何使用复合索引,如果没有有关所需集合和确切查询的更多详细信息,则很难应用于您的确切情况,但此处提供了更多信息。