【问题标题】:Sequelize many-to-many relation with custom foreign key使用自定义外键序列化多对多关系
【发布时间】:2014-06-11 14:02:51
【问题描述】:

我正在制作现有数据库的模型。我的表通过连接表具有多对多自引用。连接表有两个字段:“parent_id”和“child_id”。 我正在尝试这样定义关联:

    company.hasMany(company, {as: 'parents', foreignKey: 'child_id', through: 'company_relation'});
    company.hasMany(company, {as: 'children', foreignKey: 'parent_id',  through: 'company_relation'});

但是当我尝试设置子公司时,Sequelize 仍在联结表中寻找“children_id”外键,而不是像我定义的那样寻找“child_id”:

    company.setChildren([child]);

返回错误:

error: column company_relation.children_id does not exist

如果我不想以单数形式命名我的关联,如何在联结表中定义自定义外键,如下所示:

    company.hasMany(company, {as: 'parent', foreignKey: 'child_id', through: 'company_relation'});
    company.hasMany(company, {as: 'child', foreignKey: 'parent_id',  through: 'company_relation'});

还有其他方法吗?谢谢,如果我很难理解我很抱歉:)

【问题讨论】:

    标签: many-to-many sequelize.js


    【解决方案1】:

    阅读doc 了解关联

    我一直在调试实例然后我对此有问题,他有custom name method (set[As]) 用于关联子项(如果使用选项“as”):

    for(var method in company) {
     console.log(method);
    }
    

    我拒绝了“option.as”,因为你需要一直写它而不是 dao 模型

    【讨论】:

      【解决方案2】:

      即使您在 sequelize 关联中定义了外键,您也可能忘记在架构中定义引用。

      您可以从document查看代码 标题 : 无约束地强制执行外键引用。

      在您的情况下,您公司的定义架构如下:

      child_id:{
          references: {
              model: 'Company',
              key: 'id'
          }
      },
      parent_id:{
          references: {
              model: 'Company',
              key: 'id'
          }
      },
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2016-08-09
        • 2021-04-04
        • 1970-01-01
        • 2019-02-09
        • 1970-01-01
        • 2020-02-11
        • 2017-08-15
        • 2021-12-26
        • 2015-06-16
        相关资源
        最近更新 更多