首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bookshelf.js,查询相关表

Bookshelf.js,查询相关表
EN

Stack Overflow用户
提问于 2014-01-26 07:25:17
回答 3查看 9.6K关注 0票数 6

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

代码语言:javascript
复制
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 paragraphs.author_id != author_id)上添加where子句。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-02-10 07:17:26

代码语言:javascript
复制
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);
};
票数 1
EN

Stack Overflow用户

发布于 2014-01-31 21:23:21

这行得通吗?

代码语言:javascript
复制
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')));
});
票数 2
EN

Stack Overflow用户

发布于 2017-06-04 20:54:36

查看书架-雄辩扩展。whereHas()和with()函数可能是您要寻找的。您的功能如下所示:

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21360879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档