2015-02-24 76 views
0

如何使用通過方法檢索所有記錄,但使用中間表的條件,例如:我想檢索通道中的is_publish字段(從相冊(中間表))的所有記錄值1使用bookshelf.js過濾關係查詢

到目前爲止我的代碼看起來如下:

new channelModel({'id': req.params.channel_id}) 
.fetch({withRelated: ['tracks']}) 
.then(function (channel) { 
    if (channel) { 
     res.json({error: false, status: 200, data: channel}); 
    } else { 
     res.json({error: true, status: 404, data: 'channel does not exist'}); 
    } 
}) 

有了這個代碼,我檢索所有曲目..和信道模型定義如下的功能:

tracks: function() { 
    return this.hasMany('track').through('album'); 
} 

我的數據庫看起來水木清華這樣的:

渠道:ID,名稱,說明

專輯:CHANNEL_ID,名稱,DESCR,is_publish

曲目:album_id,名稱,DESCR

什麼建議嗎?

回答

6

我沒有測試過這一點,但我相信你可以做到以下幾點:

ChannelModel = bookshelf.BaseModel.extend({ 
    tracks: function() { 
     return this.hasMany('track').through('album'); 
    }, 
    publishedTracks: function() { 
     return this.tracks().query('where', 'is_publish', true); 
    }, 
    unpublishedTracks: function() { 
     return this.tracks().query('where', 'is_publish', false); 
    }, 
}); 

new ChannelModel({'id': req.params.channel_id}) 
.fetch({withRelated: ['pubishedTracks']}) 
.then(function (channel) { 
    if (channel) { 
     res.json({error: false, status: 200, data: channel.toJSON()}); 
    } else { 
     res.json({error: true, status: 404, data: 'channel does not exist'}); 
    } 
}); 

另外,您不妨這樣做:

new ChannelModel({'id': req.params.channel_id}) 
.fetch() 
.tap(function (channel) { 
    channel.tracks().query('where', 'is_publish', true).fetch() 
}) 
.then(function(channel) { 
    if (channel) { 
     res.json({error: false, status: 200, data: channel.toJSON()}); 
    } else { 
     res.json({error: true, status: 404, data: 'channel does not exist'}); 
    } 
}); 

而且,雖然我們在它,我可能會指出require: true,這是我喜歡這些情況下的一種風格。

new ChannelModel({'id': req.params.channel_id}) 
.fetch({ require: true }) 
.tap(function (channel) { 
    channel.tracks().query('where', 'is_publish', true).fetch() 
}) 
.then(function(channel) { 
    res.json({error: false, status: 200, data: channel.toJSON()}); 
}) 
.catch(bookshelf.NotFoundError, function(error) { 
    res.json({error: true, status: 404, data: 'channel does not exist'}); 
}); 

另外請注意,你在你的迴應呼叫離開關到.toJSON()

+0

它的工作原理...謝謝你。 – Lulzim 2015-02-25 00:25:38

+0

需要什麼:在fetch()中使用true,因爲我已經看到它在其他地方使用過...... – Lulzim 2015-02-25 00:34:13

+1

如果記錄不存在,'{require:true}'會拋出異常。這樣你就可以假設你的'then'函數的主體有記錄。 [Bluebird](https://github.com/petkaantonov/bluebird)允許通過錯誤類型捕獲錯誤,所以你可以捕獲NotFoundError並用404響應。 – 2015-02-25 02:26:21