【问题标题】:How can I model an M:N relationship using primary keys and foreign keys in place of a bridge-table with Sequelize?如何使用主键和外键代替带有 Sequelize 的桥接表来建模 M:N 关系?
【发布时间】:2021-12-18 07:03:14
【问题描述】:

这是我遇到的一种模式,在 Sequelize 文档中没有明确的示例。相信我,我搜遍了它们。

正如您在关系中看到的那样:

widget_type 主键是widget 和widget_attribute 表中的外键。

widget & widget_type 和 widget_type & widget_attribute 之间存在 M:1 和 1:N 关联。

widget_type 关系用于小部件类型的元数据。所以在这里,使用该表作为桥表很有用,而不是创建一个组合键,即小部件的主键和小部件属性的主键。

Sequelize 没有提供如何执行此操作的示例。而且,如果您像我一样没有为您的数据模型使用自动生成的命名,那么模型关联就会变得更加混乱。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:
    WidgetAttribute.belongsToMany(Widget, { as: "attributes", through: WidgetType, uniqueKey: 'widget_type', foreignKey: 'widget_type', otherKey: 'widget_type' });
    Widget.belongsToMany(WidgetAttribute, { as: "widgets", through: WidgetType, uniqueKey: 'widget_type', foreignKey: 'widget_type', otherKey: 'widget_type' });
    
    WidgetType.hasMany(WidgetAttribute, { sourceKey: 'widget_type', foreignKey: 'widget_type' });
    WidgetType.hasMany(Widget, { sourceKey: 'widget_type', foreignKey: 'widget_type' });
    
    Widget.belongsTo(WidgetType, { foreignKey: 'widget_type', targetKey: 'widget_type' });
    WidgetAttribute.belongsTo(WidgetType, { foreignKey: 'widget_type', targetKey: 'widget_type' });
    

    您可以使用模型之间的这些 Sequelize 关联创建如上所述的 M:N 关联。记住:

    • 在 WidgetAttribute 中,widget_type 是一个外键属性。

    • 在 Widget 中,widget_type 是一个外键属性。

    • 在 WidgetType 中,widget_type 是一个主键。

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      相关资源
      最近更新 更多