node.js - Bookshelf.js,关联表查询

标签 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,给定一个 scholarlyPaper id 和 author 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')));
});

关于node.js - Bookshelf.js,关联表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21360879/

相关文章:

javascript - JSON 输入的意外结束通过请求获取 Instagram JSON 数据

javascript - Neo4j连接nodejs报错

javascript - Meteor:引用不同目录中的其他javascript类

javascript - NodeJS返回的数据有时会改变

node.js - 如何批量删除书架中的 "upsert"?

javascript - 如何使用 knex 从 SQL 表中选择行值连续的情况?

javascript - Bookshelf Js多次更新数据不返回 promise

javascript - 使用 knex 和 Bookshelf 查询时如何同时使用 '<>' 和 'whereNotIn'?

node.js - 如何从子模型获取父表属性

javascript - Knex 静默转换带有时区的 Postgres 时间戳并返回不正确的时间