使用egg.js和egg-sequelize连接mysql
Posted guangzhou11
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用egg.js和egg-sequelize连接mysql相关的知识,希望对你有一定的参考价值。
egg-init --type=simple --dir=sequelize-project
cd sequelize-project
npm i
2.安装并配置 egg-sequelize 插件(它会辅助我们将定义好的 Model 对象加载到 app 和 ctx 上)和 mysql2模块:
3.
exports.sequelize = {
enable: true,
package: ‘egg-sequelize‘,
};
-
在 配置数据库信息(在
config/config.default.js
中添加 sequelize 配置)
/* eslint valid-jsdoc: "off" */ ‘use strict‘; /** * @param {Egg.EggAppInfo} appInfo app info */ module.exports = appInfo => { /** * built-in config * @type {Egg.EggAppConfig} **/ const config = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + ‘_1553528793275_7075‘; // add your middleware config here config.middleware = []; config.sequelize = { dialect: ‘mysql‘, host: ‘127.0.0.1‘, port: 3306, database: ‘egg_test‘, //数据库民 username: ‘root‘, //数据库的用户名 password: ‘root‘ // } // add your user config here const userConfig = { // myAppName: ‘egg‘, }; return { ...config, ...userConfig, }; };
使用model 连接数据表
Model/user.js
‘use strict‘; module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define(‘user‘, { userid: { type: INTEGER, primaryKey: true, autoIncrement: true }, username: STRING(50), sex: STRING(4), userpass:STRING(32) }, { freezeTableName: true, // Model 对应的表名将与model名相同 timestamps: false, } ); return User; };
5.调用model操作数据库
controller/user.js
‘use strict‘; const Controller = require(‘egg‘).Controller; class HomeController extends Controller { async index() { const { ctx } = this; ctx.body = ‘hi, egg‘; } } module.exports = HomeController;
6.创建数据库
ALTER TABLE `user` MODIFY COLUMN `userid` int(11) NOT NULL DEFAULT ‘‘ FIRST , MODIFY COLUMN `sex` char(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ‘‘ AFTER `username`;
7.添加路由
‘use strict‘; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.get(‘/‘, controller.home.index); router.get(‘/user‘, controller.user.index); };
以上是关于使用egg.js和egg-sequelize连接mysql的主要内容,如果未能解决你的问题,请参考以下文章