database - sequelize 返回手动定义的连接表的关联

标签 database postgresql sequelize.js model-associations

我正在将 Sequelize 与 Postgres 结合使用。我的两个表(estimatorListsubcontractor)由手动定义的表(estimatorSubsList)连接。

db.subcontractor.belongsToMany(db.estimatorList, { through: db.estimatorSubsList });
db.estimatorList.belongsToMany(db.subcontractor, { through: db.estimatorSubsList });

estimatorSubsList 有一个 id 和其他字段,但它也通过

关联到 contact
db.contact.hasMany(db.estimatorSubsList);

当我在数据库中查询具有特定 ID 的 estimatorList 并返回与此关联的 subcontractor(以及与分包商关联的表)时 -

db.estimatorList.findById(estimatorListId, {include:  [ { 
            model: db.subcontractor, 
            include: [  db.location, etc, etc ]
     }
    ]} )

它返回所有正确的信息。它还会自动返回 estimatorSubsList 以及每个 subcontractor 对象中的 contactId。例如:

estimatorSubsList: 
{ contactId: 1
  createdAt: ""
  estimatorListId: 1
  id:2
  otherFields:false
  subcontractorId: 2
  updatedAt:"" 
}

我的问题是,是否可以不仅获取 contactId,还获取整个联系人记录本身?我不确定如何更改返回的默认信息,或者这是否可能。我试过包含 estimatorSubsList 模型并从中包含 contact,但它根本不喜欢我尝试包含 estimatorSubsList

大家好

最佳答案

直通关系表不可能有关联。相反,您应该将其建模为单独的模型并将其包含在内:

EstimatorList.findAll({
  include: [{
    model: EstimatorSubsList,
    include: [Contact, Subcontractor]
  }]
})

确保在两个方向上都设置了所有关联。

关于database - sequelize 返回手动定义的连接表的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651082/

相关文章:

javascript - sequelize 上的多个外键(一对多或多对多)?

node.js - Sequelize : how to add one more column to primary key formed by association?

ruby-on-rails - 使用 STI 时索引去哪里了?

java - DB 机器 CPU 周期与中端机器 CPU 周期

sql - 如何在没有关键 postgres 的情况下使用 json 数组连接 2 个表

python - PyQt4 PostgreSQL QSqlQuery BC信息丢失

mysql - 如果我想优先显示某些条件,如何在 Sequelize for MySQL 中排序?

mysql - 存储具有不同属性的类似产品

database - 应用程序启动时,Mnesia disc_copies 表如何存储在 ram 中?

sql - 忽略 WHERE 子句中的特殊字符