【问题标题】:DexieJS (indexedDB) chain multiple .where clausesDexieJS (indexedDB) 链接多个 .where 子句
【发布时间】:2016-06-11 07:31:57
【问题描述】:

我正在使用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();

【问题讨论】:

    标签: javascript where-clause indexeddb dexie


    【解决方案1】:

    DexieJS 的AND 操作符可以作为过滤函数或复合索引来实现。实现查询的简单方法是使用过滤器方法,例如;

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

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

    至于如何使用复合索引,如果没有关于您想要的集合和确切查询的更多详细信息,则很难应用于您的确切情况,但是有much more information available here

    【讨论】:

    • 是的对不起,我忘了说我也试过这个collection = collection.where('Field').equals("1"). and('Field2').above(value);
    • 实际上什么都没有,我得到了一个白屏,甚至添加了.catch(function(err){ console.log(err); });。我必须说我正在使用 ngDexie 进行 Angular,也许这是一个错误
    • @ghego1 奇怪。我会暂时删除这个答案,等我有时间设置测试用例后再回来。
    • 已更新,从内存中取出并混淆了 or(使用与 where 相同类型的条件)和 and(使用过滤函数或复合索引)
    • 知道了,谢谢。然后我担心我的想法无法像我想的那样实现,我会以另一种方式设计它:-)
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2023-03-18
    • 2012-11-11
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多