2011-09-13 86 views
5

您如何處理IndexedDB中的多對多關係?IndexedDB和多對多關係

例如,假設我有一個Blog對象來存放博客文章的標籤/標籤的博客文章和Tag對象。一個Blog可以有許多Tag s,一個Tag可以被許多Blog s使用。

我會創造一個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. 的陣列
  3. Blog.tags這將是一個tagId的數組,可以用來查找Tag s。

第一種方式看起來較爲囉嗦,但它是如何在SQL中解決的。那只是我應該留下的SQL包?

我想第三種方法是讓Blog.tags成爲Tag的數組。這似乎最簡單,但我不能查詢Tag s或重複使用博客標籤(或者我可以嗎?)。

有沒有人用indexedDB處理過這種情況?如果是這樣,你最終做了什麼?有什麼陷阱?

回答

7

我正在研究IndexedDB-backed JS neural network implementation並面臨這個非常 的問題。

我們沒有在IndexedDB中進行連接,因此您至少要查看兩個對象存儲點擊,除非您正在執行某種存儲/緩存。

從經驗來看,我發現面向文檔的風格最適合於IndexedDB對象(將所有內容都存儲在同一個商店中),但需要一個輔助存儲來容納關係。

這是我正在做的。

假設你想擁有一個本地的演員和電影商店 - 就像IMDB一樣。這個和大多數多對多的關係都可以使用兩個表來建模IndexedDB:對象和關係。

下面是兩張表格。幾乎所有的東西都需要重點查找。任何不說獨特的東西都可能是非唯一的。

對象對象存儲:

type_id* 
whatever*.. 

關係對象存儲:

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

一個演員/電影的例子是兩個記錄的對象表,一個在關係表:

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電影的僞代碼:

012從某一年讓所有的電影
IndexedDBApp({ 'store': 'relationships', 'index': 'from_id', 'key': 'actor_michael_cera', 'on_success': function(row) {...}); 
// Would return movie_superbad and movie_juno rows on_success 

僞代碼:

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

僞代碼,讓所有參與者:爲獲得一部電影的演員

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

僞代碼

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