简体   繁体   English

发现 Sequelize 循环依赖

[英]Sequelize Cyclic dependency found

I get this weird error when I was trying to sync my database:当我尝试同步我的数据库时出现这个奇怪的错误:

Unhandled rejection Error: Cyclic dependency found. roles is dependent of itself.
Dependency chain: roles -> users => roles

I have this following junction table model called Permission我有以下称为 Permission 的联结表模型

const Permission = db.define('permission', {
    id: {
        type: type.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    role_id: {
        type: type.INTEGER,
        references: {
            model: 'roles',
            key: 'id',
        }
    },
    resource_id: {
        type: type.INTEGER,
        references: {
            model: 'resources',
            key: 'id',
        }
    },
});

Why does this error happen?为什么会发生这个错误? And how can I fix it?我该如何解决? In my User model, User has one Role :在我的 User 模型中, User 有一个 Role :

const User = db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    role_id : {
        type: Sequelize.INTEGER,
        references: {
            model: 'roles',
            key: 'id',
        }
    }
});

User.hasOne(Role)

Edit : Here's my Role model:编辑:这是我的角色模型:

const Role = db.define('role', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: Sequelize.STRING,
})

module.exports = Role

In sequelize docs it says:在续集文档中,它说:

The A.hasOne(B) association means that a One-To-One relationship exists between A and B, with the foreign key being defined in the target model (B) A.hasOne(B) 关联意味着 A 和 B 之间存在一对一关系,外键在目标模型 (B) 中定义

Which means, User model shouldn't have a foreign key to Role model.这意味着,用户模型不应该有角色模型的外键。 Try changing your User model to:尝试将您的用户模型更改为:

const User = db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    }

});

User.hasOne(Role)

And then your Role model to:然后你的角色模型:

const Role = db.define('role', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: Sequelize.STRING,
    user_id : {
        type: Sequelize.INTEGER,
        references: {
            model: 'users',
            key: 'id',
        }
    }
 })

Role.belongsTo(User);    

module.exports = Role

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM