1.安裝
npm i egg-bin --save-dev
2.腳手架
mkdir egg-example && cd egg-example
npm init egg --type=simple
npm i
3.安裝與鏈接數(shù)據(jù)庫(MySQL)
首先先安裝數(shù)據(jù)庫
brew install mysql
或者直接下載
鏈接數(shù)據(jù)有官方插件
npm i --save egg-mysql
找到app/config/plugin.js
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
app/config/config.default.js 中配置數(shù)據(jù)庫
exports.mysql = { // 單數(shù)據(jù)庫信息配置
client: {
host: 'mysql.com',
port: '3306',
user: 'test_user',
password: 'test_password',
database: 'test'
},
// 是否加載到 app 上矢门,默認(rèn)開啟
app: true,
// 是否加載到 agent 上睦刃,默認(rèn)關(guān)閉
agent: false
};
數(shù)據(jù)庫的增刪改查
1.查
const post = await this.app.mysql.get('posts', { id: 12 });
或者
const results = await this.app.mysql.select('posts', { // 搜索 post 表
where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE 條件
columns: ['author', 'title'], // 要查詢的表字段
orders: [['created_at','desc'], ['id','desc']], // 排序方式
limit: 10, // 返回?cái)?shù)據(jù)量
offset: 0, // 數(shù)據(jù)偏移量
});
2.增
const result = await this.app.mysql.insert('posts', { title: 'Hello World' });
3.改
const result = await this.app.mysql.update('posts', ‘hi’);
4.刪
const result = await this.app.mysql.delete('posts', {
author: 'fengmk2',
});
當(dāng)然缘琅,更復(fù)雜場(chǎng)景的我們可能需要使用Sequelize宦棺,對(duì)應(yīng)的也有插件 egg-sequelize
浑吟。
4.啟動(dòng)項(xiàng)目
npm run dev
open http://localhost:7001
5.文檔
相應(yīng)模塊具體文檔直接查看文檔