egg mysql 内连接查询_egg-sequelize连接mysql使用/egg-sequelizes数据库时间设置为东八区方案及查询日期格式化...

准备工作

在这个例子中,我们会使用 sequelize 连接到 MySQL 数据源,因此在开始编写代码之前,我们需要先在本机上安装好 MySQL,如果是 MacOS,可以通过 homebrew 快速安装:

brew install mysql

brew services start mysql

初始化项目

通过 npm 初始化一个项目:

$ mkdir sequelize-project && cd sequelize-project

$ npm init egg --type=simple

$ npm i

安装并配置 egg-sequelize 插件(它会辅助我们将定义好的 Model 对象加载到 app 和 ctx 上)和 mysql2 模块:

安装

npm install --save egg-sequelize@6.0.0 mysql2@2.2.5

在 config/plugin.js 中引入 egg-sequelize 插件

exports.sequelize = {

enable: true,

package: 'egg-sequelize',

};

在 config/config.default.js 中编写 sequelize 配置

const userConfig = {

sequelize: {

dialect: 'mysql',

host: '127.0.0.1',

port: 3306,

username: 'root',

password: '********',

database: 'test',

// 配置数据库时间为东八区北京时间

timezone: '+08:00'

}

};

return {

...config,

...userConfig,

};

编写代码

首先我们来在 app/model/ 目录下编写 user 这个 Model:

//yarn add uuid@8.3.2

//yarn add moment@2.29.1

const { v4: uuidv4 } = require('uuid');

const moment = require('moment');

module.exports = function(app) {

const { STRING, UUID, DataTypes } = app.Sequelize;

const User = app.model.define(

'User',

{

id: {

type: UUID,

unique: true,

primaryKey: true,

allowNull: false,

defaultValue: () => {

return uuidv4()

.replace(/-/g, '');

}

},

username: {

type: STRING(32),

unique: true,

allowNull: false,

comment: '用户名'

},

password: {

type: STRING(255),

allowNull: false,

comment: '密码',

},

email: {

type: STRING(64),

unique: true,

allowNull: true,

comment: '邮箱地址',

},

phone: {

type: STRING(20),

allowNull: true,

comment: '手机号码',

},

avatar: {

type: STRING(150),

allowNull: true,

comment: '头像',

},

roles: {

type: STRING(150),

allowNull: true,

comment: '权限',

},

createdAt: {

type: DataTypes.DATE,

// 对查询结果的日期进行格式化

get() {

return moment(this.getDataValue('createdAt'))

.format('YYYY-MM-DD HH:mm:ss');

}

},

updatedAt: {

type: DataTypes.DATE,

// 对查询结果的日期进行格式化

get() {

return moment(this.getDataValue('updatedAt'))

.format('YYYY-MM-DD HH:mm:ss');

}

}

},

{

// 要使用 createdAt/updatedAt 必须开启这项配置

timestamps: true,

freezeTableName: true,

// 必须开启 createdAt,updatedAt否则格式化无效

// 或这不写配置项

createdAt: true,

updatedAt: true

}

);

// 数据库同步

User.sync();//:如果数据库表不存在,则创建数据库表,如果存在,则不做任何操作

// User.sync({ force: true });//:如果数据库表已经存在,则先删除数据库表,然后重新创建数据表

// User.sync({ alter: true });//: 这个会比较数据库表当前状态(比如数据库表的列及数据类型等)与模型的不同之处,然后修改数据库表不同的地方以匹配模型。

return User;

};

使用数据库

这时service/controller层就可以进行数据库操作了

// 查询全部用户信息

async getAll() {

const { ctx } = this;

const res = await ctx.model.User.findAll();

return ctx.helper.success({ ctx, res });

}

egg-sequelize常用查询命令请参考Sequelize 中文文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值