I have the following model in Bookshelf:
var Ap = Bookshelf.Model.extend({
tableName:'aps',
idAttribute:'ethernet_mac',
hasTimestamps: true,
venue: function() {
return this.belongsTo(Venue,'venue_name');
},
switch: function() {
return this.belongsTo(Switch,'switch_id');
},
wlc: function(){
return this.belongsTo(Wlc,'wlc_id','id');
}
});
exports.Ap=Ap;
I need to make an inner join on with 4 tables and be able to query on any of the 4 table's fields. Since my "where" clauses are going to be dynamic, I am storing them in different objects according to the tables. For example: If my where clause is "where wlc.ip='1.2.3.4'AND wlc.name='w1'", the clause in stored in an object
wlcQ ={
ip:'1.2.3.4',
name:'w1'
}
Similarly, I have objects apQ for Ap, switchQ for Switch & venueQ for Venue.
If I want to query only on the Ap model, I do the following:
Ap.query(function(qb){
qb.where(apQ);
})
.fetchPage({
limit:3,
offset:0,
withRelated: [
{wlc:function(qb){qb.column('id','name','ip');}},
'switch'
]})
.then(function (resultCol){
console.log(resultCol.toJSON());
})
.catch(function (err){
console.log("Err",err);
});
I use .fetchPage as I'm using Bookshelf's pagination plugin to get 3 results per page. The above gives me 3 Ap records with all of their related switch info & only the 'id','name','ip' of their related wlc info. (3 Ap json objects with nested Wlc & Switch Json Objects)
How would I get info if there is a where clause on wlc or switch model as well?
I tried:
Ap.query(function(qb){
qb.where(apQ);
})
.fetchPage({
limit:3,
offset:0,
withRelated:[
{wlc:function(qb){qb.column('id','name','ip').where(wlcQ)}},
'switch'
]})
.then(function (resultCol){
console.log(resultCol.toJSON());
}).catch(function (err){
console.log("Err",err);
});
But this doesn't work, it gives me 3 Ap json models with nested empty Wlc json Objects. These Ap objects don't fulfill the where clause on the Wlc model.
How can I solve this issue in either Bookshelf.js or knex.js?
via acespade979
No comments:
Post a Comment