Sequelize 嵌套关联与两个表

cph*_*ill 5 associations node.js sequelize.js

我有一个场景,我试图查询具有两个关联表(引用和用户)的父表(文档),它们彼此没有关系,但与父表有关系。在 SQL 中,这个查询看起来像这样并正确输出我正在寻找的数据:

select *
from `document`
left join `user`
on `document`.`user_id` = `user`.`user_id`
left join `reference`
on `document`.`reference_id` = `reference`.`reference_id`
where `user`.`organization_id` = 1;
Run Code Online (Sandbox Code Playgroud)

但是,嵌套的关联必须按层次顺序关联,以便查询工作。由于嵌套关联彼此不相关,因此出现关联错误。我怎样才能避免这个错误?请问required: false对此有何影响?

models.Document.findAll({
  order: 'documentDate DESC',
  include: [{
    model: models.User,
    where: { organizationId: req.user.organizationId },
    include: [{
      model: models.Reference,
    }]
  }],
})
Run Code Online (Sandbox Code Playgroud)

错误

未处理的拒绝错误:引用与用户无关!

协会

Document

associate: function(db) {
  Document.belongsTo(db.User, {foreignKey: 'user_id'}),
    Document.belongsTo(db.Reference, { foreignKey: 'reference_id'});;
}
Run Code Online (Sandbox Code Playgroud)

Reference

associate: function(db){
  Reference.hasMany(db.Document, { foreignKey: 'reference_id' });
}
Run Code Online (Sandbox Code Playgroud)

我应该只链接查询吗?

dou*_*arp 4

如果您想复制查询(尽可能接近),请使用以下查询。请记住,where用户上的include只会用于删除不匹配的匹配项Document.user_idUser.organization_idDocument仍会返回 。如果您想省略User.organization_id不匹配的文档,请使用required: true.

User <- Document -> Reference

models.Document.findAll({
  // this is an array of includes, don't nest them
  include: [{
    model: models.User,
    where: { organization_id: req.user.organization_id }, // <-- underscored HERE
    required: true, // <-- JOIN to only return Documents where there is a matching User
  },
  {
    model: models.Reference,
    required: false, // <-- LEFT JOIN, return rows even if there is no match
  }],
  order: [['document_date', 'DESC']], // <-- underscored HERE, plus use correct format
});
Run Code Online (Sandbox Code Playgroud)