2015-02-09 112 views
0

我已经看过,看起来无处不在,但IndexedDb并不是非常有名。我有一个对象存储称为订单,每个订单的结构就像一个自动生成的密钥:Indexeddb搜索具有特定字段的所有订单

{"dealername":"something","dealerid":num,"totalbill":num,"items":[{},{}]} 

现在作为对象存储的订单可以有相同的dealerid多个订单,我怎么能得到所有订单与特定dealerid?

不过,对于noob问题,我来自SQL背景。 谢谢

回答

1
  1. 创建索引dealerid。
  2. 在dealerid索引上打开游标并进行迭代。

下面是一些非常简单的代码,让您开始:

function onUpgradeNeeded(event) { 
    var db = event.target.result; 

    var orderStore = db.createObjectStore('orders', ...); 

    // Create the index on dealerid here 
    orderStore.createIndex('dealeridindex', 'dealerid'); 
} 

function queryOrdersByDealerID(db, id, onOrder, onComplete) { 
    var tx = db.transaction('orders'); 
    tx.onComplete = onComplete; 
    var orders = tx.objectStore('orders'); 
    var index = orders.index('dealeridindex'); 
    var request = index.openCursor(id); 
    // You could also do this, if you wanted, it is identical: 
    // var request = index.openCursor(IDBKeyRange.only(id)); 

    request.onsuccess = function(event) { 
    var cursor = event.target.result; 
    if(!cursor) return; 
    onOrder(cursor.value); 
    cursor.continue(); 
    }; 
} 

// Now to use it: 
var openRequest = indexedDB.open('dbname', version); 

// Attach our upgrade handler that gets called when higher version found 
openRequest.onupgradeneeded = onUpgradeNeeded; 

// Now do a query 
openRequest.onsuccess = function(event) { 
    // event.target === openRequest === this 
    // use whatever you prefer, e.g. this.result or openRequest.result 
    var openDatabaseConnection = event.target.result; 

    var someId = 5; 

    function handleOrder(order){ 
    console.log('Order %o', order); 
    } 

    function whenAllMatchingOrdersIterated(event) { 
    console.log('Finished iterating over orders'); 
    } 

    // 'execute' the query 
    queryOrdersByDealerID(openDatabaseConnection, someId, 
    handleOrder, whenAllMatchingOrdersIterated); 
}