【问题标题】:Sequelize having two types of associations between two tables. (1:1 and 1:m)Sequelize 在两个表之间有两种类型的关联。 (1:1 和 1:m)
【发布时间】:2021-10-31 01:18:06
【问题描述】:

我有两个模型

  1. 文件
  2. 文档版本

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

  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 Id。

我尝试在上述关联中添加以下内容:

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

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

如何添加第二个关联?

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    当您创建约束设置为 false 的关联时,您可能会产生循环依赖。请阅读this docs

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 2016-12-03
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多