当前位置:Gxlcms > 数据库问题 > 使用EggJS开发接口(二)使用数据库之egg-sequelize

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

时间:2021-07-01 10:21:17 帮助过:174人阅读

例如:

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 没有设置自动递增

技术图片

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

标签:ase   否则   database   src   script   foreign   iar   top   update   

人气教程排行