egg+mysql(sequelize)实现增删改查

#mysql数据库中创建表
CREATE TABLE `eggs` (
  `id` int(11) NOT NULL AUTO_INCREMENT ,
  `name` varchar(255) DEFAULT NULL ,
  `birth` varchar(255) DEFAULT NULL ,
  `sign` varchar(255) DEFAULT NULL ,
  `created_at` datetime DEFAULT NULL ,
  `updated_at` datetime DEFAULT NULL ,
  PRIMARY KEY (`id`),
  UNIQUE KEY `title` (`sign`)
)CHARSET=utf8mb4 ;
安装 相关依赖
npm install egg-sequelize egg-cors --save
//配置
//config/pulgin.js
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize',
};
exports.cors = {
  enable: true,
  package: 'egg-cors',
};

//config/config.default.js
config.sequelize = {
	  dialect: 'mysql', //使用什么数据库,支持mysql,mssql,mariadb,postgres
	  dialectOptions: {
	      //utf8的超集
	      charset: 'utf8mb4',
	  },
	  database: 'eggs',
	  host: 'localhost',
	  port: '3306',
	  password: 'abcdef'
	  // 中国在东八区晚标准时间8个小时,所以时区+8,避免出现读写时间不一致
	  timezone: '+08:00',
  };
config.security = {
	  csrf: {
	    enable: false,
	  },
	  // 设置白名单地址,要发送请求到该服务器的地址
	  // domainWhiteList: []
  };
config.cors = {
    //允许携带cookie
    credentials: true,
};
//建模
// app/model/eggs.js
'use strict';

module.exports = app => {
	const {
		INTEGER,
		STRING,
		DATE
	} = app.Sequelize;
	const Eggs= app.model.define('eggs', {
		id: {
			type: INTEGER,
			primaryKey: true,
			autoIncrement: true
		},
		name: STRING,
		birth: STRING,
		sigh: STRING,
		// 后面两个sequelize会自动创建
		created_at: DATE,
		updated_at: DATE
	}, {
		freezeTableName: true, //使用默认表名
		// freezeTableName禁用修改表名;默认情况下,
		// sequelize会自动将模型名称(第一个参数定义)为复数。
		// 值为ture时不修改
		// tableName 使用的数据库表名,不写则默认是模型名称
		// timestamps是否自动添加时间戳createAt,updateAt
	})
	return Eggs;
}
// 这个 Model 就可以在 Controller 
// 和 Service 中通过 app.model.Eggs 或者 ctx.model.Eggs 访问到了,
//app/service/egg.js

'use strict';

const Service = require('egg').Service;

let ERROR = {
    code: 1,
    msg: 'failed',
  };
let SUCCESS = {
    code: 0,
    msg: 'success',
  };

class EggsService extends Service {
	async create(eggs){
		const { ctx } = this;
		try{
			// 调用sequelize的create方法,安照定义的模型传入参数创建数据
			eggs = await ctx.model.Eggs.create(eggs);
			if(!eggs){
				ctx.status = 400;
				return Object.assign(ERROR, {
					msg: `expectd eggs, but got ${JSON.stringify(eggs)}`
				});
			}
			ctx.status = 200;
			return Object.assign(SUCCESS, {
				data: eggs
			});
		}catch(e){
			ctx.status = 500;
			throw(e);
			//TODO handle the exception
		}
	}
	
	async destroy(id){
		const { ctx } = this;
		try {
			// findById已经被findByPk替代
			// 调用sequelize的findByPk方法,传入id查询数据
			const eggs = await ctx.model.Eggs.findByPk(id);
			if(!eggs) {
				ctx.status = 400;
				return Object.assign(ERROR, {
					msg: 'not found eggs'
				});
			}
			// 调用sequelize的destroy方法,将查询出来的数据删除
			const res  = await eggs.destroy();
			ctx.status = 200;
			return Object.assign(SUCCESS, {
				data: res
			})
		} catch(e) {
			ctx.status = 500;
			throw(e);
		}
	}
	
	async update({
		id,
		body
	}) {
		const { ctx } = this;
		try{
			const eggs = await ctx.model.Eggs.findByPk(id);
			if(!eggs) {
				ctx.status = 400;
				return Object.assign(ERROR, {
					msg: 'not found eggs'
				})
			}
			const res = await eggs.update(body);
			ctx.status = 200;
			return Object.assign(SUCCESS, {
				data: res
			});
		} catch(e) {
			ctx.status =  500;
			throw(e);
			//TODO handle the exception
		}
	}
	
	async find(id) {
		const { ctx } = this;
		try{
			const eggs = await ctx.model.Eggs.findByPk(id);
			if(!eggs){
				ctx.status = 400;
				return Object.assign(ERROR, {
					msg: 'not fount eggs'
				})
			}
			ctx.status = 200;
			return Object.assign(SUCCESS, {
				data: eggs
			})
		}catch(e){
			ctx.status = 500;
			throw(e)
			//TODO handle the exception
		}
	}
	
	async list({
		offset = 0,
		limit = 10,
		order_by = 'created_at',
		order = 'DESC'
	}) {
		const { ctx } = this;
		const options = {
			offset: parseInt(offset),
			limit: parseInt(limit),
			order: [
				[order_by, order.toUpperCase()]
			]
		}
		try{
			const res = await ctx.model.Eggs.findAndCountAll(options);
			if(!res){
				ctx.status = 400;
				return Object.assign(ERROR, {
					msg: 'not found eggs'
				})
			}
			ctx.status = 200;
			return Object.assign(SUCCESS, {
				data: res
			})
		}catch(e){
			ctx.status = 500;
			throw(e);
			//TODO handle the exception
		}
	}
}

module.exports = EggsService;
//app/controller/egg.js
'use strict';

const Controller = require('egg').Controller;

class EggsController extends Controller {
	async create(){
		const { ctx } = this;
		const body = ctx.request.body;
		console.log(body, 'mynameisbody');
		ctx.body = await ctx.service.eggs.create(body);
	}
	async destroy(){
		const { ctx } = this;
		const id = +ctx.params.id; //隐式变换
		console.log(id);
		ctx.body = await ctx.service.eggs.destroy(id);
	}
	async update(){
		const { ctx } = this;
		const id = +ctx.params.id;
		const body = ctx.request.body;
		ctx.body = await ctx.service.eggs.update({
			id,
			body
		})
	}
	async find(){
		const { ctx } = this;
		const id = +ctx.params.id;
		ctx.body = await ctx.service.eggs.find(id);
	}
	async list() {
		const { ctx } = this;
		const query = ctx.query;
		ctx.body = await ctx.service.eggs.list(query);
	}
}

module.exports = EggsController;
//router.js
  router.post('/api/eggs',controller.eggs.create);
  router.delete('/api/eggs/:id', controller.eggs.destroy);
  router.put('/api/eggs/:id', controller.eggs.update);
  router.get('/api/eggs', controller.eggs.list);
  router.get('/api/eggs/:id', controller.eggs.find);

然后就可以使用postman进行调试了
链接: egg-sequelize 链接多个数据库.

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于 Egg.js 和 MySQL增删改查语句,你可以借助 Egg.js 提供的框架特性和 MySQL 的 npm 包来完成。以下是一些示例代码: 1. 安装依赖: ``` $ npm install egg-mysql --save ``` 2. 配置插件: 在 `config/plugin.js` 中添加以下配置: ``` exports.mysql = { enable: true, package: 'egg-mysql' }; ``` 3. 配置数据库连接: 在 `config/config.default.js` 中添加以下配置(根据你自己的实际情况修改): ``` exports.mysql = { client: { host: 'localhost', port: '3306', user: 'root', password: 'your_password', database: 'your_database' } }; ``` 4. 使用增删改查语句: 在 Controller 或 Service 中使用以下示例代码来执行相应的 SQL 操作。 注意:这里只是示例,你需要根据具体的业务逻辑进行修改。 - 查询数据: ```javascript const res = await app.mysql.get('table_name', { id: 1 }); // 获取 id 为 1 的数据 const res = await app.mysql.select('table_name', { where: { status: 1 }, orders: [[ 'create_time', 'desc' ]], limit: 10 }); // 获取 status 为 1 的前 10 条数据,按照创建时间降序排列 ``` - 插入数据: ```javascript const res = await app.mysql.insert('table_name', { name: 'example' }); // 插入一条数据,name 字段为 'example' ``` - 更新数据: ```javascript const res = await app.mysql.update('table_name', { name: 'new_example' }, { where: { id: 1 } }); // 更新 id 为 1 的数据,将 name 字段更新为 'new_example' ``` - 删除数据: ```javascript const res = await app.mysql.delete('table_name', { id: 1 }); // 删除 id 为 1 的数据 ``` 这只是一些基本的示例,你可以根据需要使用更复杂的查询条件和操作。具体的语法和用法可以参考 Egg.js 和 MySQL 的官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值