在我的模型中有一个Users表和一个UserPhones表。 User.id是UserPhones中的外键。
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
userid : {
type : DataTypes.UUID,
primaryKey : true,
},
username : DataTypes.STRING,
},
{
classMethods: {
associate: (models) => {
models.User.hasOne(models.UserPhone, {foreignKey: 'userId'});
}
}
});
return User;
};
module.exports = (sequelize, DataTypes) => {
const UserPhone = sequelize.define('UserPhone', {
id : {
type : DataTypes.UUID,
primaryKey : true,
},
userId : {
type : DataTypes.UUID,
references: {
model : require('.').User,
key : 'userid',
deferrable: sequelize.Deferrable.INITIALLY_IMMEDIATE
}
},
phoneNumber : {
type: DataTypes.STRING
}
},
{
classMethods: {
associate: (models) => {
models.UserPhone.belongsTo(models.User, {foreignKey: 'userId'});
}
}
}
);
return UserPhone;
};
销毁手机号码很简单:
UserPhone.destroy({where: {phoneNumber: '123456789'}};
我想删除所有具有sequelize特定电话号码的用户。 更好的是,删除所有拥有一组电话号码的用户。
答案 0 :(得分:5)
我认为不可能同时执行DELETE和JOIN查询。
因此,
我想删除所有具有sequelize特定电话号码的用户。
UserPhone.findAll({attributes: ['userId'], where: {phoneNumber: '1234'}}
.then(function (userIds) {
if (userIds.length === 0)
return Promise.resolve(true) //nothing to delete
return User.destroy({where: {id: {$in: userIds}}});
})
删除所有拥有一组电话号码的用户。
var array = ['123', '456'];
UserPhone.findAll({attributes: ['userId'], where: {phone: { $in: array }}}
.then(function (userIds) {
if (userIds.length === 0)
return Promise.resolve(true) //nothing to delete
return User.destroy({where: {id: {$in: userIds}}});
})
答案 1 :(得分:0)
Sequelize当前不支持include
方法上的destroy
选项:https://sequelize.org/master/class/lib/model.js~Model.html#static-method-destroy
如果要避免使用多个sql语句,则必须编写原始查询: https://sequelize.org/master/manual/raw-queries.html
例如
await sequelize.query(`
DELETE User
FROM User
INNER JOIN UserPhone ON UserPhone.userId = User.userId
WHERE UserPhone.phoneNumber = :phoneNumber
`, { replacements: { phoneNumber: '1234'} })