我目前使用 Dexie.js 在本地存储数据。我有 3 个不同的表,它们通过使用外键相互连接。我设法设置了架构并插入了相应的数据。但是,当我要检索数据时,却找不到如何连接不同表的示例。
下面是一个例子:
var db = new Dexie('my-testing-db');
db.delete().then(function() {
db.version(1).stores({
genres: '++id,name',
albums: '++id,name,year,*tracks',
bands: '++id,name,*albumsId,genreId'
});
db.transaction('rw', db.genres, db.albums, db.bands, function() {
var rock = db.genres.add({
name: 'rock'
}),
jazz = db.genres.add({
name: 'jazz'
});
var justLookAround = db.albums.add({
name: 'Just Look Around',
year: 1992,
tracks: [
'We want the truth', 'Locomotive', 'Shut me out'
]
});
var sickOfItAll = db.bands.add({
name: 'Sick Of it All'
});
justLookAround.then(function(album_id) {
rock.then(function(rock_id) {
sickOfItAll.then(function(band_id) {
db.bands.update(band_id, {
genreId: rock_id,
albumsId: [album_id]
}).then(function(updated) {
});
});
});
});
}).then(function() {
//how to join the tables here????
db.bands.each(function(band) {
console.log(band);
});
});
});
Run Code Online (Sandbox Code Playgroud)
以下是加入结果的方法。免责声明:代码未经测试!
\nvar all = Dexie.Promise.all;\n\nfunction joinBands (bandCollection) {\n\n // Start by getting all bands as an array of band objects\n return bandCollection.toArray(function(bands) {\n\n // Query related properties:\n var genresPromises = bands.map(function (band) {\n return db.genres.get(band.genreId || 0);\n });\n var albumsPromises = bands.map(function (band) {\n return db.albums.where('id').anyOf(band.albumsId || []).toArray();\n });\n\n // Await genres and albums queries:\n return all ([\n all(genresPromises),\n all(albumsPromises)\xc2\xa8\n ]).then(function (genresAndAlbums) {\n\n // Now we have all foreign keys resolved and\n // we can put the results onto the bands array\n // before returning it:\n bands.forEach(function (band, i) {\n band.genre = genresAndAlbums[0][i];\n band.albums = genresAndAlbums[1][i];\n });\n return bands;\n });\n });\n}\n\n// Join all:\njoinBands(db.bands.toCollection()).then(function (bands) {\n alert ("All bands: " + JSON.stringify(bands, null, 4));\n}).catch(function (error) {\n alert ("Oops: " + error);\n});\n\n// Query and join:\njoinBands(db.bands.where('genreId').anyOf([1,5,19]).limit(25)).then(function (bands) {\n alert ("Some bands: " + JSON.stringify(bands, null, 4));\n}).catch (function (error) {\n alert ("Oops: " + error);\n});\nRun Code Online (Sandbox Code Playgroud)\n最好从事务中调用 joinBands() 以加快查询速度并获得更可靠和原子的结果。
\n