主要目录结构
app
|
|--controller
| |--many.js
|--model
| |--title.js
| |--sub.js
|--service
| |--titles.js
|--router.js
"use strict"
module.exports = (app)=>{
const {
STRING
} = app.Sequelize;
const Title = app.model.define('title',{
id: STRING,
title_id: {
type: STRING,
primaryKey: true
},
subtitle: STRING,
title: STRING
}, {
freezeTableName:true,
timestamps: false
})
return Title
}
"use strict"
module.exports = (app)=>{
const {
STRING
} = app.Sequelize;
const Sub = app.model.define('sub_item',{
id: STRING,
sub_item_id: {
type: STRING,
primaryKey: true
},
sub_item: STRING,
father_id: STRING
}, {
freezeTableName:true,
timestamps: false
})
return Sub
}
"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(id);
const res2 = await ctx.model.Sub.findByPk('1_1');
if(!res) {
ctx.status = 400;
return { msg: 'not found'}
}
return {data: {...res, ...res2}}
} catch(e){
throw(e)
}
}
}
module.exports = TitleService;
"use strict"
const Controller = require('egg').Controller;
class ManyController extends Controller {
async getMsg(){
this.ctx.body = await this.ctx.service.titles.find('1');
}
}
module.exports = ManyController;
'use strict';
module.exports = app => {
const { router, controller } = app;
router.get('/info', controller.many.getMsg);
};
链接: egg-sequelize 链接多个数据库.