我有四张table:校长、老师、学生和班级。教师、学生和班级之间存在着一种多对多的关系。现在我想从校长到老师、学生和班级建立一对多的关系。
我已经写了这段代码,但它只是将headid添加到student表中。如何将headid添加到其他表中?
这是head表格中的代码:
const bcrypt = require('bcrypt');
const bcrypt_p = require('bcrypt-promise');
const jwt = require('jsonwebtoken');
const {TE, to} = require('../../services/util.service');
const CONFIG = require('../../config/config');
/* jshint ignore:start*/
module.exports = (sequelize, DataTypes) => {
var Model = sequelize.define('Head', {
first : DataTypes.STRING,
last : DataTypes.STRING,
email : {type: DataTypes.STRING, allowNull: true, unique: true,
validate: { isEmail: {msg: "Email invalid."} }},
phone : {type: DataTypes.STRING, allowNull: true, unique: true,
validate: { len: {args: [7, 20], msg: "Phone number invalid, too short."},
isNumeric: { msg: "not a valid phone number."} }},
password : DataTypes.STRING,
});
Model.associate = function(models){
this.Heads = this.hasMany(models.Class, {as: 'ClassAdmins'});
};
Model.associate = function(models){
this.Classes = this.belongsTo(models.Head);
};
Model.associate = function(models){
this.Heads = this.hasMany(models.Teacher, {as: 'TeacherAdmins'});
};
Model.associate = function(models){
this.Teachers = this.belongsTo(models.Head);
};
Model.associate = function(models){
this.Heads = this.hasMany(models.Student, {as: 'StudentAdmins'});
};
Model.associate = function(models){
this.Students = this.belongsTo(models.Head);
};
Model.beforeSave(async (user, options) => {
let err;
if (user.changed('password')){
let salt, hash
[err, salt] = await to(bcrypt.genSalt(10));
if(err) TE(err.message, true);
[err, hash] = await to(bcrypt.hash(user.password, salt));
if(err) TE(err.message, true);
user.password = hash;
}
});
Model.prototype.comparePassword = async function (pw) {
let err, pass
if(!this.password) TE('password not set');
[err, pass] = await to(bcrypt_p.compare(pw, this.password));
if(err) TE(err);
if(!pass) TE('invalid password');
return this;
}
Model.prototype.getJWT = function () {
let expiration_time = parseInt(CONFIG.jwt_expiration);
return "Bearer "+jwt.sign({user_id:this.id}, CONFIG.jwt_encryption,
{expiresIn: expiration_time});
};
Model.prototype.toWeb = function (pw) {
let json = this.toJSON();
return json;
};
return Model;
};
/*jshint ignore:end*/
感谢您的帮助
1条答案
按热度按时间gudnpqoy1#
我想我可以通过这个改变来解决这个问题:
把所有的hasmany放在一个模型中。关联并且没有任何blongsto
我的解决方案: