gpt4 book ai didi

javascript - 发现 Sequelize 循环依赖

转载 作者:行者123 更新时间:2023-12-03 22:35:47 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com