IndexedDB和多对多关系

时间:2011-09-13 20:45:34

标签: javascript html5 indexeddb

你们如何处理IndexedDB中的多对多关系?

例如,假设我有一个Blog对象来保存博客帖子,Tag对象用于博客帖子的标签/标签。一个Blog可以包含多个Tag个,Tag可以使用一个Blog

我会创建一个blog storetag store(虽然我愿意接受建议)来容纳这两种类型的对象:

// ...
var blogStore = db.createObjectStore("blog", {keyPath: "blogId", autoIncrement: true});
blogStore.createIndex("title", "title", {unique: true});
var tagStore = db.createObjectStore("tag", {keyPath: "tagId", autoIncrement: true});
tagStore.createIndex("label", "label", {unique: true});

我可以想到两种方法将两者联系起来:

  1. 有一个Blog.tags,它是BlogTag个对象的数组,其中包含blogIdtagId(并且也会在商店中进行检索)或
  2. Blog.tagstagId数组,可用于查找Tag
  3. 第一种方式看似啰嗦,但这是如何在SQL中解决的。那只是我应该留下的SQL行李吗?

    我认为第三种方法是让Blog.tags成为Tag的数组。这似乎最简单,但后来我无法查询Tag或跨博客重用标签(或者我可以吗?)。

    有没有其他人使用indexedDB处理过这种情况?如果是这样,你最终做了什么?有什么陷阱?

1 个答案:

答案 0 :(得分:7)

我正在研究IndexedDB-backed JS neural network implementation并面对此问题 问题。

我们没有IndexedDB中的连接,因此除非您正在进行某种记忆/缓存,否则您至少要查看两个对象存储点击。

根据经验,我发现面向文档的样式最适合使用IndexedDB对象(将所有内容存储在同一个商店中),但需要一个辅助存储来存放关系。

这就是我正在做的事情。

假设您想拥有一个本地商店的演员和电影 - 就像IMDB一样。这个以及大多数任何多对多关系都可以使用IndexedDB使用两个表建模:对象和关系。

这是两张桌子。几乎所有东西都需要密钥查找*。任何不说独特的东西都可以是非独特的。

对象对象存储:

type_id*
whatever*..

关系对象存储:

id* (unique, auto-incrementing)
from_type*
to_id*

演员/电影示例将是Objects表中的两个记录,以及关系表中的一个记录:

var actor1 = {
    id: 'actor_jonah_goldberg',
    display: 'Jonah Goldberg',
};

var actor2 = {
    id: 'actor_michael_cera',
    display: 'Michael Cera'
};

var movie1 = {
    id: 'movie_superbad',
    display: 'Superbad',
    year: 2007
};

var movie2 = {
    id: 'movie_juno',
    display: 'Juno',
    year: 2007
};

//relationship primary key ids are auto-inc

var relationship1 = {
    from_id: 'actor_jonah_goldberg',
    to_id: 'movie_superbad'
} 

var relationship2 = {
    from_id: 'actor_michael_cera',
    to_id: 'movie_superbad'
} 

var relationship3 = {
    from_id: 'actor_michael_cera',
    to_id: 'movie_juno'
} 

获得Michael Cera电影的Psuedo代码:

IndexedDBApp( { 'store': 'relationships', 'index': 'from_id', 'key': 'actor_michael_cera', 'on_success': function( row ) {...} );
// Would return movie_superbad and movie_juno rows on_success

用于获取特定年份所有电影的Psuedo代码:

IndexedDBApp( { 'store': 'objects', 'index': 'year', 'key': 2007, 'on_success': function( row ) {...} );
// Would return movie_superbad and movie_juno rows on_success

用于获取电影演员的Psuedo代码:

IndexedDBApp( { 'store': 'relationships', 'index': 'to_id', 'key': 'movie_superbad', 'on_success': function( row ) {...} );
// Would return actor_jonah_goldberg and actor_michael_cera on_success

获得所有演员的Psuedo代码:

IndexedDBApp( { 'store': 'relationships', 'index': 'id', 'cursor_begin': 'actor_a', 'cursor_end': 'actor_z', 'on_success': function( row ) {...} );
// Would return actor_jonah_goldberg and actor_michael_cera on_success