我正在使用Sequelize.js v1.7.9。使用Express.js 4
我有以下关系:
User hasMany UserRoles
User hasMany Roles through UserRoles
UserRoles belongsTo user
UserRoles belongsTo role
Role hasMany UserRoles
Role hasMany Users through UserRoles
在Rails中,我们可以简单地说依赖:: destroy,当删除User
或Role
时,相关的UserRole
行也会被销毁,但这不起作用与Sequelize.js。
我使用迁移显式创建连接表,我在连接表上设置了onDelete:'CASCADE'。但它的表现并不像预期的那样。
TL; DR,如何删除CASCADE以像Rails ActiveRecord一样工作dependent: :destroy
我的代码如下:
user.js的:
module.exports = function (sequelize, DataTypes) {
var user = sequelize.define('user',
{
name: DataTypes.STRING,
},
{
classMethods: {
associate: function (models) {
user.hasMany(models.role, {through: models.userRole})
user.hasMany(models.userRole, {onDelete: 'CASCADE', hooks: true})
}
}
}
)
return user
}
role.js:
module.exports = function (sequelize, DataTypes) {
var role = sequelize.define('role',
{
name: DataTypes.STRING,
},
{
classMethods: {
associate: function (models) {
role.hasMany(models.userRole, {onDelete: 'CASCADE', hooks: true})
role.hasMany(models.user, {through: models.userRole})
}
}
}
)
return role
}
userRole.js:
module.exports = function (sequelize, DataTypes) {
var userRole = sequelize.define('userRole',
{
userId: DataTypes.INTEGER,
roleId: DataTypes.INTEGER,
},
{
classMethods: {
associate: function (models) {
userRole.belongsTo(models.user)
userRole.belongsTo(models.role)
}
}
}
)
return userRole
}
由于
答案 0 :(得分:3)
不幸的是,n:m级联在1.7中无法正常工作。它们默认添加在2.0
中