我如何在MySQL Nodejs中建立一对多关系?

时间:2018-10-27 22:22:46

标签: javascript mysql node.js sequelize.js one-to-many

我有4张桌子:校长,老师,学生和班级。 老师,学生和班级之间存在多对多关系。 现在,我想从头到老师,学生和班级建立一对多的关系。

我已经编写了这段代码,但只是将 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 个答案:

答案 0 :(得分:0)

我想我可以通过此更改解决它:

  

将所有 hasMany 放入一个Model.associate,并且没有任何blongsTo

我的解决方案:

Model.associate = function(models){
    this.Heads = this.hasMany(models.Class, {as: 'ClassAdmins'});
    this.Heads = this.hasMany(models.Teacher, {as: 'TeacherAdmins'});
    this.Heads = this.hasMany(models.Student, {as: 'StudentAdmins'});
};