我正在尝试构建一个使用以下(一对多键值对,即每个id有多个图像)数据结构的IndexedDB应用程序:
var images = [{"id": "1", "img":["img1","img2","img3"]},
{"id": "1", "img":["img4","img5","img6"]}]
我的问题是如何使用此结构。所有示例都要遍历所有键,或者只有一个与每个键相关联的值,它们可以轻松获得。我可以在get('id')方法上打开游标并遍历该id的所有“img”项吗? 这是我目前尝试的内容:
1)获取特定密钥(一对一映射):
var dbGet = function(id, cbGet){
var transaction = db.transaction(["images"],"readonly");
var objectStore = transaction.objectStore("images");
var request = objectStore.get(id);
request.onerror = function(event) {};
request.onsuccess = function(e) {
if(typeof(e.target.result) != "undefined"){
cbGet(null,null,e.target.result);
}
};
};
2)获取所有密钥:
var dbGetAll = function(id){
var transaction = db.transaction(["images"],"readonly");
var objectStore = transaction.objectStore("images");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
//Do something
cursor.continue();
}
};
}
3)如何获得特定密钥的“全部”(一对多映射)?
答案 0 :(得分:0)
我自己找到了答案,并将其发布给其他可能正在努力解决这个问题的人:
1)获取给定键的现有值数组:
function getExisting(id, object){
var existingImgArr = new Array();
var transaction = db.transaction(["images"],"readonly");
var objectStore = transaction.objectStore("images");
var request = objectStore.get(id);
request.onerror = function(event) {
};
request.onsuccess = function(e) {
if(typeof(e.target.result) != "undefined"){
existingImgArr = (e.target.result.img);
}
dbSaveWithExisting(id, object,existingImgArr);
};
2)其次,在上面的成功回调中,调用另一个函数追加到现有的val数组:
function appendToExisting(id, object, imgArr){
var transaction = db.transaction(["images"], "readwrite");
transaction.oncomplete = function(event) {};
transaction.onerror = function(event) {};
var objectStore = transaction.objectStore("images");
imgArr.push(object.value);
var data = {"id": id,
"img": imgArr
};
var request = objectStore.put(data);
request.onsuccess = function(event) {};
}
答案 1 :(得分:0)