Bookshelf.js,查询相关表

时间:2014-01-26 07:25:18

标签: node.js bookshelf.js knex.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和作者ID,我怎样才能得到作者没有写一个段落的论文中的所有部分?

我面临的特殊挑战是我无法在相关表格上添加where子句(例如'where paragraphs.author_id!= author_id)。

3 个答案:

答案 0 :(得分:2)

这有用吗?

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

查看bookshelf-eloquent扩展程序。 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();
}