準(zhǔn)備工作
在這個(gè)例子中小腊,我們會(huì)使用 sequelize 連接到 MySQL 數(shù)據(jù)源伏尼,因此在開始編寫代碼之前脖旱,我們需要先在本機(jī)上安裝好 MySQL,如果是 MacOS介蛉,可以通過 homebrew 快速安裝:
brew install mysql
brew services start mysql
初始化項(xiàng)目
通過 npm 初始化一個(gè)項(xiàng)目:
$ mkdir sequelize-project && cd sequelize-project
$ npm init egg --type=simple
$ npm i
安裝并配置 egg-sequelize 插件(它會(huì)輔助我們將定義好的 Model 對(duì)象加載到 app 和 ctx 上)和 mysql2 模塊:
- 安裝
npm install --save egg-sequelize@6.0.0 mysql2@2.2.5
- 在 config/plugin.js 中引入 egg-sequelize 插件
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
- 在 config/config.default.js 中編寫 sequelize 配置
const userConfig = {
sequelize: {
dialect: 'mysql',
host: '127.0.0.1',
port: 3306,
username: 'root',
password: '********',
database: 'test',
// 配置數(shù)據(jù)庫(kù)時(shí)間為東八區(qū)北京時(shí)間
timezone: '+08:00'
}
};
return {
...config,
...userConfig,
};
編寫代碼
首先我們來在 app/model/ 目錄下編寫 user 這個(gè) Model:
//yarn add uuid@8.3.2
//yarn add moment@2.29.1
const { v4: uuidv4 } = require('uuid');
const moment = require('moment');
module.exports = function(app) {
const { STRING, UUID, DataTypes } = app.Sequelize;
const User = app.model.define(
'User',
{
id: {
type: UUID,
unique: true,
primaryKey: true,
allowNull: false,
defaultValue: () => {
return uuidv4()
.replace(/-/g, '');
}
},
username: {
type: STRING(32),
unique: true,
allowNull: false,
comment: '用戶名'
},
password: {
type: STRING(255),
allowNull: false,
comment: '密碼',
},
email: {
type: STRING(64),
unique: true,
allowNull: true,
comment: '郵箱地址',
},
phone: {
type: STRING(20),
allowNull: true,
comment: '手機(jī)號(hào)碼',
},
avatar: {
type: STRING(150),
allowNull: true,
comment: '頭像',
},
roles: {
type: STRING(150),
allowNull: true,
comment: '權(quán)限',
},
createdAt: {
type: DataTypes.DATE,
// 對(duì)查詢結(jié)果的日期進(jìn)行格式化
get() {
return moment(this.getDataValue('createdAt'))
.format('YYYY-MM-DD HH:mm:ss');
}
},
updatedAt: {
type: DataTypes.DATE,
// 對(duì)查詢結(jié)果的日期進(jìn)行格式化
get() {
return moment(this.getDataValue('updatedAt'))
.format('YYYY-MM-DD HH:mm:ss');
}
}
},
{
// 要使用 createdAt/updatedAt 必須開啟這項(xiàng)配置
timestamps: true,
freezeTableName: true,
// 必須開啟 createdAt萌庆,updatedAt否則格式化無效
// 或這不寫配置項(xiàng)
createdAt: true,
updatedAt: true
}
);
// 數(shù)據(jù)庫(kù)同步
User.sync();//:如果數(shù)據(jù)庫(kù)表不存在,則創(chuàng)建數(shù)據(jù)庫(kù)表币旧,如果存在践险,則不做任何操作
// User.sync({ force: true });//:如果數(shù)據(jù)庫(kù)表已經(jīng)存在,則先刪除數(shù)據(jù)庫(kù)表吹菱,然后重新創(chuàng)建數(shù)據(jù)表
// User.sync({ alter: true });//: 這個(gè)會(huì)比較數(shù)據(jù)庫(kù)表當(dāng)前狀態(tài)(比如數(shù)據(jù)庫(kù)表的列及數(shù)據(jù)類型等)與模型的不同之處巍虫,然后修改數(shù)據(jù)庫(kù)表不同的地方以匹配模型。
return User;
};
使用數(shù)據(jù)庫(kù)
這時(shí)service/controller層就可以進(jìn)行數(shù)據(jù)庫(kù)操作了
// 查詢?nèi)坑脩粜畔? async getAll() {
const { ctx } = this;
const res = await ctx.model.User.findAll();
return ctx.helper.success({ ctx, res });
}