Bookshelf.js,在相关表上查询

我有一个类似于以下的模型:

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); } }); 

使用Bookshelf.js,给出一个学术论文编号和作者ID,我怎样才能得到作者没有写一个段落的论文中的所有部分?

我面临的特殊挑战是我不知道在相关表上添加where子句(例如,where paragraphs.author_id!= author_id)。

这是否工作?

 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); }; 

看看书架 – 雄辩的扩展。 whereHas()和with()函数可能是你正在寻找的。 你的函数看起来像这样:

 async function(authorId, paperId) { return await ScholarlyPaper.where('id', paperId) .with('sections', (q) { // Filter out sections in the paper that the author did not write a single paragraph in. q.whereHas('paragraphs', (q) => { q.where('author_id', authorId); }, '<=', 0); }).first(); }