Sequelize.JS是node里面比較常用的一個ORM(對象映射模型),提供了很多豐富的接口,egg-sequelize是基於其做的一個egg項目下的ORM插件
安裝:
npm install egg-sequelize mysql2 -S // 或者 yarn add egg-sequelize mysql2
導入到egg項目中:
// 在config/plugin.js里面添加 exports.sequelize = { enable: true, package: 'egg-sequelize' } // 或者,在config/plugin.js的module.exports里面添加 module.exports = { sequelize: { enable: true, package: 'egg-sequelize' }, };
配置:
config.sequelize = { dialect: 'mysql', // 表示使用mysql host: '127.0.0.1', // 連接的數據庫主機地址 port: 3306, // mysql服務端口 database: 'diary', // 數據庫名 username: 'root', // 數據庫用戶名 password: 'root', // 數據庫密碼 define: { // model的全局配置 timestamps: true, // 添加create,update,delete時間戳 paranoid: true, // 添加軟刪除 freezeTableName: true, // 防止修改表名為復數 underscored: false // 防止駝峰式字段被默認轉為下划線 }, timezone: '+8:00', // 由於orm用的UTC時間,這里必須加上東八區,否則取出來的時間相差8小時 dialectOptions: { // 讓讀取date類型數據時返回字符串而不是UTC時間 dateStrings: true, typeCast(field, next) { if(field.type === "DATETIME"){ return field.string(); } return next(); } } };
注:在默認情況下,id
字段會被設置為主鍵,並且是AUTO_INCREMENT
的,不需要我們自己聲明;
例如:
app/model/user.js
/** * 用戶模型 */ module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, autoIncrement: true, primaryKey: true }, name: { type: STRING, allowNull: false }, password: { type: STRING(32), allowNull: false } }); // 表關聯的字段 User.associate = function() { // 一對多 app.model.User.hasMany(app.model.Diary, { foreignKey: 'user_id', targetKey: 'id'}) } return User; }
app/model/diary.js
/** * 日志模型 */ module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const Diary = app.model.define('diary', { id: { type: INTEGER, autoIncrement: true, primaryKey: true }, title: { type: STRING, allowNull: false }, content: { type: STRING, allowNull: false } }); // 表關聯的字段 Diary.associate = function() { app.model.Diary.belongsTo(app.model.User, { foreignKey: 'user_id', targetKey: 'id'}) } return Diary; }
在 controller 中調用 model:
app/controller/home.js
'use strict'; const Controller = require('egg').Controller; class HomeController extends Controller { async index() { const { ctx } = this; ctx.body = 'hi, egg'; } // 添加日志 async add() { const { ctx } = this; // 從前端獲取post請求發來的數據 const param = ctx.request.body; const result = await ctx.model.Diary.create({ title: param.title, content: param.content, user_id: 2 }); console.log('add方法', result); if(result){ ctx.body = '創建成功'; }else{ ctx.body = '創建失敗'; } } // 登錄判斷 async loginCheck() { const { ctx } = this; // // 關聯查詢 // const data = await ctx.model.User.findAll({ // include: { // model: ctx.model.Diary // } // }); // ctx.body = data; // post請求傳來的參數 const { name, password } = ctx.request.body; let message = '', data = {}; // 判斷數據庫里面是否存在該用戶 const user = await ctx.model.User.findOne({ where: { name: name } }); if(!user){ message = '用戶不存在'; }else if(password !== user.password){ message = '密碼錯誤'; }else{ message = '登錄成功'; data = { id: user.id }; } ctx.body = { message, data }; } } module.exports = HomeController;
注:Field 'id' doesn't have a default value 解決方案
原因 id 沒有設置自動遞增