如何使用through方法检索所有记录但是具有中间表的条件,例如:我想检索一个频道的所有曲目,其中来自专辑(中间表)的is_publish字段的值为1
到目前为止,我的代码如下所示: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,name,desc
相册:CHANNEL_ID,名称,DESCR,is_publish
轨道:album_id,名称,DESCR
有什么建议吗?
答案 0 :(得分:7)
我还没有测试过这个,但我相信你可以做到以下几点:
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()
。