egg-sequelize链接同一个数据库的多个表

主要目录结构
app
|
|--controller
|  |--many.js
|--model
|  |--title.js
|  |--sub.js
|--service
|  |--titles.js
|--router.js

// title.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
}

// sub.js
"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
}

// 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(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;
// 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');
	}
}
module.exports = ManyController;
// route.js
'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/info', controller.many.getMsg);
};

链接: egg-sequelize 链接多个数据库.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值