首页 文章

用自定义外键续订多对多关系

提问于
浏览
1

我正在制作现有数据库的模型 . 我的表通过联结表具有多对多的自引用 . 连接表有两个字段:'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'});

还有其他方法吗?谢谢,对不起,如果我很难理解:)

2 回答

  • 2

    阅读关于关联的这个doc

    我一直调试实例然后我有这个问题,他有custom name method (set[As])为关联子项(如果使用选项"as"):

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

    我拒绝了“option.as”,因为你需要所有的时间来代替dao模型

  • 0

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

    您可以检查document Headers 中的代码:在没有约束的情况下强制执行外键引用 .

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

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

    希望这会对你有所帮助

相关问题