使用EggJS开发接口(二)使用数据库之egg-sequelize

Sequelize.JS是node里面比较常用的一个ORM(对象映射模型),提供了很多丰富的接口,egg-sequelize是基于其做的一个egg项目下的ORM插件

安装:

npm install egg-sequelize mysql2 -S
// 或者
yarn add egg-sequelize mysql2

导入到egg项目中:

// 在config/plugin.js里面添加
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize'
}
 
// 或者,在config/plugin.js的module.exports里面添加
module.exports = {
  sequelize: {
    enable: true,
    package: 'egg-sequelize'
  },
};
配置:
config.sequelize = {
  dialect: 'mysql', // 表示使用mysql
  host: '127.0.0.1', // 连接的数据库主机地址
  port: 3306, // mysql服务端口
  database: 'diary', // 数据库名
  username: 'root', // 数据库用户名
  password: 'root', // 数据库密码
  define: { // model的全局配置
    timestamps: true, // 添加create,update,delete时间戳
    paranoid: true, // 添加软删除
    freezeTableName: true, // 防止修改表名为复数
    underscored: false // 防止驼峰式字段被默认转为下划线
  },
  timezone: '+8:00', // 由于orm用的UTC时间,这里必须加上东八区,否则取出来的时间相差8小时
  dialectOptions: { // 让读取date类型数据时返回字符串而不是UTC时间
    dateStrings: true,
    typeCast(field, next) {
      if(field.type === "DATETIME"){
        return field.string();
      }
      return next();
    }
  }
};

注:在默认情况下,id字段会被设置为主键,并且是AUTO_INCREMENT的,不需要我们自己声明

例如:

app/model/user.js

/**
 * 用户模型
 */
module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;
  const User = app.model.define('user', {
    id: {
      type: INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    name: {
      type: STRING,
      allowNull: false
    },
    password: {
      type: STRING(32),
      allowNull: false
    }
  });

  // 表关联的字段
  User.associate = function() {
    // 一对多
    app.model.User.hasMany(app.model.Diary, { foreignKey: 'user_id', targetKey: 'id'})
  }

  return User;
}

app/model/diary.js

/**
 * 日志模型
 */
module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;
  const Diary = app.model.define('diary', {
    id: {
      type: INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    title: {
      type: STRING,
      allowNull: false
    },
    content: {
      type: STRING,
      allowNull: false
    }
  });

  // 表关联的字段
  Diary.associate = function() {
    app.model.Diary.belongsTo(app.model.User, { foreignKey: 'user_id', targetKey: 'id'})
  }

  return Diary;
}

在 controller 中调用 model:

app/controller/home.js

'use strict';

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

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  // 添加日志
  async add() {
    const { ctx } = this;
    // 从前端获取post请求发来的数据
    const param = ctx.request.body;
    const result = await ctx.model.Diary.create({
      title: param.title,
      content: param.content,
      user_id: 2
    });
    console.log('add方法', result);
    if(result){
      ctx.body = '创建成功';
    }else{
      ctx.body = '创建失败';
    }
  }

  // 登录判断
  async loginCheck() {
    const { ctx } = this;
    // // 关联查询
    // const data = await ctx.model.User.findAll({
    //   include: {
    //     model: ctx.model.Diary
    //   }
    // });
    // ctx.body = data;

    // post请求传来的参数
    const { name, password } = ctx.request.body;
    let message = '', data = {};
    // 判断数据库里面是否存在该用户
    const user = await ctx.model.User.findOne({
      where: {
        name: name
      }
    });

    if(!user){
      message = '用户不存在';
    }else if(password !== user.password){
      message = '密码错误';
    }else{
      message = '登录成功';
      data = { id: user.id };
    }

    ctx.body = {
      message,
      data
    };
  }
}

module.exports = HomeController;

注:Field 'id' doesn't have a default value 解决方案

原因 id 没有设置自动递增

posted @ 2020-03-20 12:00  每天都要进步一点点  阅读(5821)  评论(0编辑  收藏  举报