我目前正在使用 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);
});
});
});
最佳答案
不幸的是,我是从谷歌来到这里寻找实际连接的,你知道的,类似的东西:
db.bands.where(...).equals(..).join(
db.genres.where(...).etc(), 'genreId -> genres.id').then(
function(band, genre) { ... });
这个,我认为更接近于原提问者的提问,但是根据@david-fahlander 提供的答案,似乎这个插件,https://github.com/ignasbernotas/dexie-relationships ,如果你想构建一个漂亮的对象树,可能会更容易一些。
该插件的自述文件与您的示例非常相似,因此我将其逐字复制到此处:
架构
注意设置外键的 ->
的使用。
import Dexie from 'dexie'
import relationships from 'dexie-relationships'
var db = new Dexie('MusicBands', {addons: [relationships]})
db.version(1).stores({
genres: 'id, name',
bands: 'id, name, genreId -> genres.id',
albums: 'id, name, bandId -> bands.id, year'
});
用法
db.bands
.where('name').startsWithAnyOf('A', 'B') // can be replaced with your custom query
.with({albums: 'albums', genre: 'genreId'}) // makes referred items included
.then(bands => {
// Let's print the result:
bands.forEach (band => {
console.log (`Band Name: ${band.name}`)
console.log (`Genre: ${band.genre.name}`)
console.log (`Albums: ${JSON.stringify(band.albums, null, 4)}`)
});
})
关于javascript - Dexie.js - 如何连接表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594184/