通过多个键从indexedDB获取所有数据

问题描述 投票:0回答:1

如何通过2个或更多键从indexedDB获取数据?例如,我有一个以image_code为索引的images_store。说我有:

image_code | image_value
img_aaa000 | ###########
img_bbb111 | #######$$.#
img_ccc222 | ###5%######
img_ddd333 | #.###***###

我想从图像代码“ img_bbb111”和“ img_ddd333”获取数据,就像我从SQL查询它一样:

SELECT * FROM images_store WHERE image_code IN ("img_bbb111","img_ddd333");

谢谢!

indexeddb
1个回答
0
投票

您需要发出多个查询。 SQL IN运算符本质上是image_code = a or image_code = b的语法糖。问题是此处使用or。 indexedDb不支持or之类的东西。因此,您需要对img_bbb111发出查询,然后对img_ddd333进行第二次查询,然后将这两个查询的结果合并。

类似这样的东西:

function myOnUpgradeNeeded(event) {
   const imageStore = db.createObjectStore('images_store', ...);
   imageStore.createIndex('image_code_index', 'image_code');
}

function findImagesForCodes(db, codes) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('images_store');
    const store = transaction.objectStore('images_store');
    const codeIndex = store.index('image_code_index');

    const results = [];

    transaction.oncomplete = event => resolve(results);
    transaction.onerror = event => reject(event.target.error);

    for (const code of codes) {
      const request = codeIndex.get(code);
      request.onsuccess = onRequestSuccess;
    }

    function onRequestSuccess(event) {
      const image = event.target.result;
      if(image) {
        results.push(image);
      }
    }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.