node.js - Sequelize 嵌套关联与两个表

标签 node.js associations 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;

但是,嵌套的关联必须按层次顺序关联才能使查询起作用。由于嵌套关联彼此不相关,因此出现关联错误。我怎样才能避免这个错误? required: false 对此有什么影响吗?

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

错误:

Unhandled rejection Error: reference is not associated to user!

关联:

文档:

associate: function(db) {
  Document.belongsTo(db.User, {foreignKey: 'user_id'}),
    Document.belongsTo(db.Reference, { foreignKey: 'reference_id'});;
}

引用:

associate: function(db){
  Reference.hasMany(db.Document, { foreignKey: 'reference_id' });
}

我应该改为链式查询吗?

最佳答案

如果您想(尽可能接近地)复制您的查询,请使用以下查询。请记住 where关于用户include只会用于删除 Document.user_id 上的匹配项User.organization_id在哪里不匹配,但是 Document仍然会被退回。如果要省略 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
});

关于node.js - Sequelize 嵌套关联与两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987364/

相关文章:

mysql - 使用mysql在 Node js中进行嵌套查询

node.js - 防止字段在初始设置后更新

mysql - CakePHP 3.x - 跨多个表保存关联数据

ruby-on-rails - 在事件管理员列中显示回形针图像

ruby-on-rails - 哪个 MVC 层应该处理 child 领取玩具?

node.js - 如何在 AWS Lambda Node.js 运行时异步发出 HTTP 请求

javascript - 在 ExpressJS Generator 中,Views 文件夹有什么用?

sql - 将列更新为具有相同 ID 的另一行中该列的任何非未知值

javascript - Sequelize hasOne 关联限制

node.js - 在 google cloud sql nodejs 上定义 Sequelize