javascript - 发现 Sequelize 循环依赖

标签 javascript node.js sequelize.js

当我尝试同步我的数据库时出现这个奇怪的错误:

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

我有以下称为 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',
        }
    },
});

为什么会发生这个错误?我该如何解决?在我的 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)

编辑:这是我的 Angular 色模型:
const Role = db.define('role', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: Sequelize.STRING,
})

module.exports = Role

最佳答案

在 Sequelize 文档中,它说:

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)



这意味着,用户模型不应该有 Angular 色模型的外键。尝试将您的用户模型更改为:
const User = db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    }

});

User.hasOne(Role)

然后你的 Angular 色模型:
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

关于javascript - 发现 Sequelize 循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60853047/

相关文章:

mysql - Sequelize.js 将别名关联与非别名关联一起加入

javascript - 未引用脚本的 Console.log

arrays - 如何将复合类型的数组从 nodejs 传递到 postgresql 函数?

node.js - 发布-订阅设计模式

javascript - NodeJS-App - DOM 操作?

mysql - Sequelize(或清除 SQL)查询以选择包含 JSON 字段值的行?

sequelize.js - Sequelize : What happens if you insert a record with fields that are not in the database

javascript - “文档”与 'content.document'

javascript - 如何在 MongoDB 的多个嵌套数组中插入和查找对象?

javascript - 带有 promise 链的 Typeorm 复杂查询