Sequelize两个表之间有两种类型的关联.(1:1和1:1)



我有两个模型

文件
  1. documentVersions

这两个模型有两种不同类型的关联:

  1. 一个文档有多个文档版本:
Document.hasMany(models.DocumentVersion, {
foreignKey: { name: 'documentId', allowNull: false },
sourceKey: 'id',
onDelete: 'cascade',
as: 'documentVersion'
});

DocumentVersion.belongsTo(models.Document, {
foreignKey: { name: 'documentId', allowNull: false },
targetKey: 'id',
onDelete: 'cascade',
as: 'document'
});

在文档版本模型中创建一个documentId外键可以很好地工作。

  1. 每个文档都有一个活动的documentVersion。所以文档模型应该有一个活动的documentVersion Id。

我试着在上面的关联中添加以下内容:

Document.hasOne(models.DocumentVersion, {
foreignKey: { name: 'activeVersionId', allowNull: false },
targetKey: 'id',
as: 'activeDocumentVersion'
});

但这最终在documentVersion表中添加了activeVersionId,而不是文档表。

如何添加第二个关联?

任何帮助将是非常感激的。提前谢谢。

当您创建约束设置为false的关联时,可以使用循环依赖。请阅读这些文档

Document.belongsTo(models.DocumentVersion, {
foreignKey: { name: 'activeVersionId', allowNull: false },
targetKey: 'id',
constraints: false,
as: 'activeDocumentVersion'
});

最新更新