Sequelize实现一对一,一对多,多对多关联

var SysUser = sequelize.import('../models/SysUser.js');
var MonitorSetting = sequelize.import('../models/MonitorSetting.js');
var Car = sequelize.import('../models/Car.js');
var Camera = sequelize.import('../models/Camera');
var Course = sequelize.import('../models/Course');
var Teacher = sequelize.import('../models/Teacher');
var TeacherToCourse = sequelize.import('../models/TeacherToCourse');

首先是一对一:

const Sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {

    const MonitorSetting = sequelize.define('MonitorSettings', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            allowNull: false,
            autoIncrement: true
        },
        uId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            field: 'u_id'
        },
        username: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: ''
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: ''
        },
        salt: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: ''
        },
        equiNumber: {
            type: DataTypes.STRING,
            allowNull: false,
            field: 'equi_number',
            defaultValue: ''
        },
        ipAddress: {
            type: DataTypes.STRING,
            allowNull: false,
            field: 'ip_address',
            defaultValue: '127.0.0.1'
        },
        position: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: ''
        },
        stability: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0
        },
        deployedAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: Sequelize.NOW,
            field: 'deployed_at'
        },
        latitude: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: ''
        },
        longitude: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: ''
        },
        levelUpAddress: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '',
            field: 'level_up_address'
        },
        currentVersion: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '',
            field: 'current_version'
        },
        isDel: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0,
            field: 'is_del'
        }
    }, {
        timestamps: false,
        underscored: true,
        // paranoid: true,
        freezeTableName: true,
        tableName: 'MonitorSettings',
        charset: 'utf8',
        collate: 'utf8_general_ci'
    });

    return MonitorSetting;
}
const Sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {

  const SysUser = sequelize.define('SysUsers', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
      unique: true
    },
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: '',
      unique: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    salt: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    status: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0
    },
    header: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    phone: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    lastIpAddress: {
      field: 'last_ip_address',
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    sex: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0
    },
    birthday: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false
    },
    qq: {
      type: DataTypes.STRING,
      defaultValue: '',
      allowNull: false
    },
    createdAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW,
      field: 'created_at',
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW,
      field: 'created_at',
      allowNull: false
    },
    isDel: {
      field: 'is_del',
      type: DataTypes.INTEGER,
      defaultValue: 0,
      allowNull: false
    }
  }, {
    timestamps: false,
    underscored: true,
    // paranoid: true,
    freezeTableName: true,
    tableName: 'SysUsers',
    charset: 'utf8',
    collate: 'utf8_general_ci'
  })

  return SysUser;
};

我们首先定义了两个Model,马上为它们建立关系:

SysUser.hasOne(MonitorSetting,{foreignKey: 'uId',sourceKey: 'id'});
MonitorSetting.belongsTo(SysUser, {foreignKey: 'uId',targetKey: 'id'});

当我们通过SysUser.findOne(查询条件)获得一个User实体的时候,我们可以继续关联得到MonitorSetting实体:

比如: 

   async (req, res, next) => {  
        var user = await SysUser.findOne({ where: { id: 1} });
        var monitor = await user.getMonitorSetting(这儿也是可以传入查询条件的);
    } 

然后是一对多:

const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {
     const Car =  sequelize.define('Cars', {
         id: {
             type: DataTypes.INTEGER,
             primaryKey: true,
             allowNull: false,
             autoIncrement: true,
             unique: true
         },
         cameraId: {
             type: DataTypes.INTEGER,
             field: 'camera_id',
             allowNull: false
         },
         carColor: {
            type: DataTypes.STRING,
            field: 'car_color',
            allowNull: false,
            defaultValue: ''
         },
         carBoardType: {
            type: DataTypes.STRING,
            field: 'car_board_type',
            allowNull: false,
            defaultValue: ''
         },
         carBoardPosition: {
            type: DataTypes.STRING,
            field: 'car_board_position',
            allowNull: false,
            defaultValue: ''
         },
         carFullName: {
            type: DataTypes.STRING,
            field: 'car_full_name',
            allowNull: false,
            defaultValue: ''
         },
         carBrand: {
            type: DataTypes.STRING,
            field: 'car_brand',
            allowNull: false,
            defaultValue: ''
         },
         carType: {
            type: DataTypes.STRING,
            field: 'car_type',
            allowNull: false,
            defaultValue: ''
         },
         carColorType: {
            type: DataTypes.STRING,
            field: 'car_color_type',
            allowNull: false,
            defaultValue: ''
         },
         carMainColor: {
            type: DataTypes.STRING,
            field: 'car_main_color',
            allowNull: false,
            defaultValue: ''
         },
         carSecondaryColor: {
            type: DataTypes.STRING,
            field: 'car_secondary_color',
            allowNull: false,
            defaultValue: ''
         },
         carFullImg: {
            type: DataTypes.STRING,
            field: 'car_full_img',
            allowNull: false,
            defaultValue: ''
         },
         carNumberImg: {
            type: DataTypes.STRING,
            field: 'car_number_img',
            allowNull: false,
            defaultValue: ''
         },
         carNumber: {
            type: DataTypes.STRING,
            field: 'car_number',
            allowNull: false,
            defaultValue: ''
         },
         entryDate: {
            type: DataTypes.DATE,
            field: 'entry_date',
            allowNull: false,
            defaultValue: Sequelize.DATE
         },
         leaveDate: {
            type: DataTypes.DATE,
            field: 'leave_date',
            allowNull: true,
            defaultValue: Sequelize.DATE
         },
         isDel: {
             type: DataTypes.INTEGER,
             allowNull: false,
             field: 'is_del',
             defaultValue: 0
         }
     }, {
        timestamps: false,
        underscored: true,
        // paranoid: true,
        freezeTableName: true,
        tableName: 'Cars',
        charset: 'utf8',
        collate: 'utf8_general_ci'
     });

     return Car;
}
const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {
    const Camera = sequelize.define('Cameras',{
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            unique: true,
            allowNull: false,
            autoIncrement: true
        },
        mId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: '',
            field: 'm_id'
        },
        persistFilePath: {
            type: DataTypes.STRING,
            allowNull: false,
            field: 'persist_file_path',
            defaultValue: ''
        },
        equiNumber: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '',
            field: 'equi_number'
        },
        equiModel: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '',
            field: 'equi_model'
        },
        port: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0
        },
        status: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0
        },
        ipAddress: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '',
            field: 'ip_address'
        },
        markPosition: {
            type: DataTypes.STRING,
            field: 'mark_position',
            defaultValue: '',
            allowNull: false
        },
        isDel: {
            type: DataTypes.INTEGER,
            field: 'is_del',
            defaultValue: 0,
            allowNull: false
        }
    },{
        timestamps: false,
        underscored: true,
        // paranoid: true,
        freezeTableName: true,
        tableName: 'Cameras',
        charset: 'utf8',
        collate: 'utf8_general_ci'
     });

     return Camera;
}

然后建立关联关系:

Camera.hasMany(Car,{
  foreignKey:'cameraId',sourceKey:'id', as: 'Cars'
})
Car.belongsTo(Camera, {
  foreignKey:'cameraId',targetKey:'id', as: 'Camera'
})

对于Camera来说,Car可以有很多个,对于Car来说,就是唯一的一个Camera与它对应,这儿的as相对于把抓取对象重命名了一下,当获得一个Camera对象之后,使用方法如: await camera.getCars();

最后是多对多:

为了让表的建立可控,我采用的是手动建立中间表的方式做的。

const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {

    const Teacher = sequelize.define('Teachers',{
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        teacherName: {
            type: DataTypes.STRING,
            field: 'teacher_name',
            allowNull: false,
            defaultValue: ''
        },
        isDel: {
            type: DataTypes.INTEGER,
            field: 'is_del',
            allowNull: false,
            defaultValue: 0
        }
    },{
        timestamps: false,
        underscored: true,
        // paranoid: true,
        freezeTableName: true,
        tableName: 'Teachers',
        charset: 'utf8',
        collate: 'utf8_general_ci'
     });

    return Teacher;
}
const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {
    
    const Course = sequelize.define('Courses',{
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        courseName: {
            type: DataTypes.STRING,
            field: 'course_name',
            allowNull: false,
            defaultValue: ''
        },
        isDel: {
            type: DataTypes.INTEGER,
            field: 'is_del',
            allowNull: false,
            defaultValue: 0
        }
    },{
        timestamps: false,
        underscored: true,
        // paranoid: true,
        freezeTableName: true,
        tableName: 'Courses',
        charset: 'utf8',
        collate: 'utf8_general_ci'
     });

    return Course;
}

const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {

    const TeacherToCourse = sequelize.define('TeacherToStudent',{
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        tId: {
            type: DataTypes.INTEGER,
            field: 't_id',
            allowNull: false,
            defaultValue: 0
        },
        courseId: {
            type: DataTypes.INTEGER,
            field: 'course_id',
            allowNull: false,
            defaultValue: 0
        },
        isDel: {
            type: DataTypes.INTEGER,
            field: 'is_del',
            allowNull: false,
            defaultValue: 0
        }
    },{
        timestamps: false,
        underscored: true,
        // paranoid: true,
        freezeTableName: true,
        tableName: 'TeacherToCourse',
        charset: 'utf8',
        collate: 'utf8_general_ci'
     });

    return TeacherToCourse;
}

最后,我们建立多对多的关系(也可以不用自己手动建立中间表,可以参考官网的自动建表方式)

Teacher.belongsToMany(Course, { as: 'Courses', through: TeacherToCourse, foreignKey: 'tId' })
Course.belongsToMany(Teacher, { as: 'Teachers', through: TeacherToCourse, foreignKey: 'courseId' })

对于获取关联对象的方法均如第一个形式一致,在此不赘述。

更多用法请参考官方文档:传送门


你可能感兴趣的:(nodejs)