我有以下型号: 用户,类型和地址 用户属于流派 用户归属于地址
输入以下代码:
const bcrypt = require('bcrypt');
/*Validation unique msg error*/
class Genre extends Model {}
Genre.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
name:{
type: Sequelize.STRING(45)
}
},{
sequelize,
timestamps: false,
tableName: "geners",
})
class Address extends Model {}
Address.init({
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
cep: {
type: Sequelize.STRING(9),
allowNull: false,
validate: {
notNull: {
args: true,
msg: 'Preencha o campo CEP'
}
}
},
complement: {
type: Sequelize.STRING(9)
}
},{
sequelize,
timestamps: false,
tableName: "adressess",
hooks: {
beforeSave(address){
console.log(address)
}
}
})
class User extends Model {}
User.init({
// attributes
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
email: {
type: Sequelize.STRING(70),
allowNull: false,
validate: {
isEmail: {
args: true,
msg: 'Digite um e-mail válido.'
},
notNull: {
args: true,
msg: 'Preencha este campo'
}
},
unique: {
args: true,
msg: 'Este e-mail já está sendo utilizado!'
}
},
password: {
type: Sequelize.STRING(15),
allowNull: false,
validate:{
len: {
args: [5,10],
msg: 'A senha deve possuir entre 5 e 10 caracteres.'
},
notNull: {
args: true,
msg: 'Preencha este campo'
}
}
}
}, {
sequelize,
tableName: "persons",
timestamp: false,
hooks: {
beforeCreate: (user) => {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
},
beforeBulkUpdate: (user) => {
console.log(user.attributes.password)
if (user.attributes.password) {
const salt = bcrypt.genSaltSync();
user.attributes.password = bcrypt.hashSync(user.attributes.password, salt);
}
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password);
}
},
modelName: 'user'
// options
});
User.hasOne(Administrator,{foreignKey: 'personId'})
Administrator.belongsTo(User,{foreignKey: 'personId'})
User.hasOne(PhysicalPerson,{foreignKey: 'personId'})
PhysicalPerson.belongsTo(User,{foreignKey: 'personId', as: 'pperson'})
User.belongsTo(Address,{foreignKey: 'addressId'})
Address.hasOne(User,{foreignKey: 'addressId'})
可以很好地插入,但是如果对任何模型的验证之一失败,则保存另一个模型。
示例:
如果我跑步
User.create({
"email": "felipe21rod@gmail.com",
"password": "123456789",
"PhysicalPerson": {
"cpf": "-66",
"birth": "1991-08-31",
"name": null,
"genreId": 2,
"Address": {
"cep": "38706-202"
}
}
})
PhysicalPerson的验证失败,因为"name": null
,但是在数据库上创建了地址和用户数据,我该如何防止呢?