I have a model similar to the following:
var ScholarlyPaper = Bookshelf.Model.extend({
tableName: 'papers',
paragraphs: function() {
return this.hasMany(Paragraph).through(Section);
},
sections: function() {
return this.hasMany(Section);
}
});
var Section = Bookshelf.Model.extend({
tableName: 'sections',
paragraphs: function() {
return this.hasMany(Paragraph);
}
scholarlyPaper: function() {
return this.belongsTo(ScholarlyPaper);
}
});
var Paragraph = Bookshelf.Model.extend({
tableName: 'paragraphs',
section: function() {
return this.belongsTo(Section);
},
scholarlyPaper: function() {
return this.belongsTo(ScholarlyPaper).through(Section);
},
author: function() {
return this.belongsTo(Author);
}
});
var Author = Bookshelf.Model.extend({
tableName: 'authors',
paragraphs: function() {
return this.hasMany(Paragraph);
}
});
Using Bookshelf.js, given a scholarlyPaper id and author id, how can I get all of the sections in the paper that the author did not write a single paragraph in?
The particular challenge I am facing is that there is no way that I am aware of to add a where clause on a related table (e.g 'where paragraphs.author_id != author_id).
Does this work?
new ScholarlyPaper({id: 1}).load({paragraphs: function(qb) {
qb.where('paragraphs.author_id', '!=', author_id);
}}).then(function(paper) {
console.log(JSON.stringify(paper.related('paragraphs')));
});
function(authorId, paperId, success, failure) {
new ScholarlyPaper({id: paperId}).load({sections: function(qb) {
qb.whereNotExists(function() {
this.from('paragraph')
.whereRaw('paragraph.section = section.id')
.where('paragraph.author_id', '=', authorId);
});
}}).then(function(paper) {
success(paper.related('section'));
}, failure);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With