主要目录结构
app
|
|--controller
| |--many.js
|--model
| |--title.js
|--model2
| |--title2.js
|--service
| |--titles.js
| |--titles2.js
|--router.js
config
|--config.default.js
// config.default.js
config.sequelize = {
// 定义多个数据库使用
datasources: [
{
dialect: 'mysql',
dialectOptions: {
charset: 'utf8mb4',
},
database: 'test1',
host: 'localhost',
port: '3306',
password: '1234567',
timezone: '+08:00',
},
{
// 通过egg的app或者ctx访问这个模型的字段
// 默认是model,也就是app.model.xx
// 这里是通过app.Model2来使用db1数据库的模型
delegate: 'Model2',
// 指定模型文件在哪里,默认是model
// 如果是在子目录如model/xx,要保证model没被单独使用
baseDir: 'model2',
dialect: 'mysql',
dialectOptions: {
charset: 'utf8mb4',
},
database: 'db1',
host: 'localhost',
port: '3306',
password: '1234567',
timezone: '+08:00',
},
]
}
// model/title.js
"use strict"
module.exports = app=>{
const {
STRING
} = app.Sequelize;
// 这个模型的文件名是小写的
// 所以要大写首字母,是egg的约定,不然会访问不到
// 一些其他的命名规则
// user.js app.model.User
// person.js app.model.Person
// user_group.js app.model.UserGroup
// user/profile.js app.model.User.Profile
const Title = app.model.define('title',{
id: STRING,
title_id: {
type: STRING,
primaryKey: true
},
subtitle: STRING,
title: STRING
}, {
freezeTableName:true,
timestamps: false
})
return Title
}
// model2/title2.js
"use strict"
module.exports = app=>{
const {
INTEGER,
STRING,
DATE
} = app.Sequelize;
const Title2 = app.Model2.define('student1',{
Id: {
type: STRING,
},
age1: INTEGER,
name: STRING,
birth: DATE
}, {
freezeTableName: true,
timestamps: false
})
return Title2;
}
// service/titles.js
"use strict"
const Service = require('egg').Service;
class TitleService extends Service {
async find(id){
const { ctx } = this;
try {
const res = await ctx.model.Title.findByPk('1');
// findByPk(find by primary key)
// 假设id是主键
// 那么findByPk('1') 的条件就是where id='1';
if(!res) {
ctx.status = 400;
return { msg: 'not found'}
}
return {data: res}
} catch(e){
throw(e)
}
}
}
module.exports = TitleService;
// service/titles2.js
"use strict"
const Service = require('egg').Service;
class Title2Service extends Service {
async find(id){
try{
const { ctx } = this;
const res = await ctx.Model2.Title2.findOne({where: {name: id}})
if(!res){
return {
err: 'not found'
}
}
return {
data: res
}
}catch(e){
throw(e)
}
}
}
module.exports = Title2Service;
// controller/many.js
"use strict"
const Controller = require('egg').Controller;
class ManyController extends Controller {
async getMsg(){
this.ctx.body = await this.ctx.service.titles.find('1');
}
async getMsg2(){
this.ctx.body = await this.ctx.service.titles2.find('1');
}
}
module.exports = ManyController;
'use strict';
module.exports = app => {
const { router, controller } = app;
router.get('/info', controller.many.getMsg);
router.get('/info2', controller.many.getMsg2)
};
还有一些其他字段可以看下面这篇
链接: egg+mysql(sequelize)实现增删改查.
链接: egg-sequelize链接同一个数据库的多个表.