我看了看,到处都看,但是IndexedDb并不是很有名。我有一个名为orders的对象库,它带有一个自动生成的密钥,每个订单的结构如下:
{"dealername":"something","dealerid":num,"totalbill":num,"items":[{},{}]}
现在,由于objectstore订单可以包含多个具有相同dealerid的订单,我如何获得具有特定dealerid的所有订单?
抱歉,对于noob问题,我来自SQL背景。 感谢
答案 0 :(得分:1)
以下是一些非常简单的代码,可以帮助您入门:
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);
}