使用EggJS开发接口(二)使用数据库之egg-sequelize
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用EggJS开发接口(二)使用数据库之egg-sequelize,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2365字,纯文字阅读大概需要4分钟。
内容图文
![使用EggJS开发接口(二)使用数据库之egg-sequelize](/upload/InfoBanner/zyjiaocheng/521/c615bc5d5403465cbc63bcffc99f0d71.jpg)
例如:
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
本文系统来源:https://www.cnblogs.com/crazycode2/p/12445929.html
内容总结
以上是互联网集市为您收集整理的使用EggJS开发接口(二)使用数据库之egg-sequelize全部内容,希望文章能够帮你解决使用EggJS开发接口(二)使用数据库之egg-sequelize所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。