1.安装sequelize依赖和mysql驱动
cnpm i egg-sequelize mysql2 -save
2.在config/plugin.js 下启用sequelize插件
sequelize:{
enable:true,
package:'egg-sequelize'
}
3.在 config/config.default.js 配置数据库
config.sequelize = {
dialect: 'mysql',
database: 'test',
host: '127.0.0.1',
port: '3306',
username: 'root',
password: '123456',
timezone: '+08:00',
dialectOptions: {
dateStrings: true,
typeCast(field, next) {
if (field.type === "DATETIME") {
return field.string();
}
return next();
}
}
};
4.定义model , 在app/model 目录 下新建一个文件 test.js
module.exports = app => {
const { STRING,INTEGER,DATE} = app.Sequelize;
const Test = app.model.define('test',
{
id: {
type: INTEGER,
primaryKey: true
},
name:{
type: STRING(50)
},
status:{
type: INTEGER
},
create_time:{
type: DATE
}
},
{
freezeTableName: true,
timestamps: false,
}
);
Test.associate = function() {
app.model.Test.hasMany(app.model.Test2, {foreignKey:'id',sourceKey:'test_id' });
app.model.Test.belongsTo(app.model.Test3, {foreignKey:'id',targetKey:'test_id' });
};
return Test ;
};
5.操作符
const Op = Sequelize.Op
[Op.and]: {a: 5}
[Op.or]: [{a: 5}, {a: 6}]
[Op.gt]: 6,
[Op.gte]: 6,
[Op.lt]: 10,
[Op.lte]: 10,
[Op.ne]: 20,
[Op.eq]: 3,
[Op.not]: true,
[Op.between]: [6, 10],
[Op.notBetween]: [11, 15],
[Op.in]: [1, 2],
[Op.notIn]: [1, 2],
[Op.like]: '%hat',
[Op.notLike]: '%hat'
[Op.iLike]: '%hat'
[Op.notILike]: '%hat'
[Op.startsWith]: 'hat'
[Op.endsWith]: 'hat'
[Op.substring]: 'hat'
[Op.regexp]: '^[h|a|t]'
[Op.notRegexp]: '^[h|a|t]'
[Op.iRegexp]: '^[h|a|t]'
[Op.notIRegexp]: '^[h|a|t]'
[Op.like]: { [Op.any]: ['cat', 'hat']}
[Op.overlap]: [1, 2]
[Op.contains]: [1, 2]
[Op.contained]: [1, 2]
[Op.any]: [2,3]