Can I create relationships between my object stores in IndexedDB?
For example, I have two object stores: artist
and album
. An artist
has a one-to-many relationship with an album
. album.artistId
relates the album to artist.id
.
I'm thinking along the lines of Hibernate here. I would like to do a query for artists and have the albums belonging to that artist returned as an array called artists
on the album
object.
artist.albums = [];
There are some great answers below that answer the question very well. I'd like to add that I was originally trying to use IndexedDB as a relational store and build an ORM-like solution on top of it, which it is not suited for. IndexedDB is a NoSQL database and since I've started treating it that way it's made more sense and my projects easier to manage. I hope this adds some value to the original question for those who continually come across it.
In IndexedDB, relationship is just reference to other store. In this case, artist
store's id is indexed field, artistId
, in album
store. In this way, you can quickly query using key range query.
Using ydn.db.Storage database wrapper,
var schema = [stores: [
{name: 'artist'},
{name: 'album',
indexes: [
{name: 'artistId'}
]
}
];
db = new ydn.db.Storage('dbname', schema)
suppose, we are interst in artist, aid.
db.get('artist', aid).success(function(artist ) {
db.query('album', 'artistId').only(aid).success(function(albums) {
// display artist and albums
})
});
The indexedDB provides low level methods to create, read, update, and delete (CRUD) "records" of objects. But the standard does not define specific methods for relational operations. The goal was to keep the standard simple and allow developers to implement the higher-level functions in any way they saw fit. However, what you're asking for is still attainable through a small amount of development on your part.
To help things out, Parashuram Narasimhan wrote a Jquery implementation for indexedDB that will finish the job for you.
Jquery indexedDB Example 1
Jquery indexedDB Example 2
Consider the following generalized possibility:
$.indexeddb("MyDatabase")
.objectStore("Artist")
.openCursor()
.each(function(){
//Got Artist
//Enumerate for Albums
$.indexeddb("MyDatabase")
.objectStore("Artist")
.openCursor()
.each(function(){
//Check for matching artist.Id
//if this albums's artist matches artist
//then do something
}
;
}
;
A little late for an answer, but I hope it helps grease the gears a bit.
You could also try using LINQ2IndexedDB - another library that uses LINQ style queries for IndexedDB - http://linq2indexeddb.codeplex.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With