表之間的關聯關系有三種:一對一,一對多,多對多。要進行多表操作,首先要建立表與表之間的關聯關系,在sequelize中分別使用hasOne,hasMany和belongsToMany表示以上三中關系。例如我們要建立user表與role表的多對多的關聯,可以這樣寫,首先要建立外鍵(當然也可以在兩張表之間建立中間表)
本文主要完成多表操作簡單的部分,熟悉在多表中建立關聯關系並且可以完成簡單的聯表操作,以聯表查詢為例。
需求
- 登錄成功時返回結果中要包含角色信息,以便展示對應的權限菜單
- 查詢用戶時返回結果中要包含角色名稱
約定
- 登錄(POST)
- 傳參:
- Body: nickname(必填), password(必填)
- 成功: {code:200,msg:'登錄成功',token,roleid}
- 失敗: {code:400,msg:'登錄失敗'}
- 查詢所有用戶(GET)
- 傳參
- 成功: {code:200,msg:'查詢成功',data}
- 失敗: {code:400,msg:'查詢失敗'}
實現
- 數據庫結構,user增加roleid
- 目錄結構
- app/model/user.js
'use strict'; module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, nickname: STRING(20), password: STRING(50), roleid: INTEGER, }, { timestamps: false, }); User.associate = function() { app.model.User.belongsTo(app.model.Role, { foreignKey: 'roleid', targetKey: 'id', as: 'role' }); }; return User; };
- app/service/user.js
'use strict'; const Service = require('egg').Service; const crypto = require('crypto'); // 設置默認密碼 const DEFAULT_PWD = '123456'; function toInt(str) { if (typeof str === 'number') return str; if (!str) return str; return parseInt(str, 10) || 0; } class UserService extends Service { // 查詢user表,驗證密碼和花名 async validUser(nickname, password) { const data = await this.ctx.model.User.findAll(); const pwd = this.getMd5Data(password); for (const item of data) { if (item.nickname === nickname && item.password === pwd) return item; } return false; } // 獲取用戶,不傳id則查詢所有 async getUser(id) { const { ctx } = this; const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) }; if (id) { return await ctx.model.User.findByPk(toInt(id)); } return await ctx.model.User.findAll({ query, attributes: [ 'nickname' ], include: [{ model: ctx.model.Role, as: 'role', attributes: [ 'name' ], }], }); } // 新增人員 async addUser(nickname) { const { ctx } = this; const password = this.getMd5Data(DEFAULT_PWD); await ctx.model.User.create({ nickname, password }); } // 修改密碼 async editPwd(id, password) { const { ctx } = this; const user = await ctx.model.User.findByPk(id); const newPwd = this.getMd5Data(password); await user.update({ password: newPwd }); } // 專門對數據進行md5加密的方法,輸入明文返回密文 getMd5Data(data) { return crypto.createHash('md5').update(data).digest('hex'); } } module.exports = UserService;
- app/controller/user.js
'use strict'; const Controller = require('egg').Controller; class UserController extends Controller { // 登錄 async login() { const { ctx, app } = this; const data = ctx.request.body; // 判斷該用戶是否存在並且密碼是否正確 const getUser = await ctx.service.user.validUser(data.nickname, data.password); if (getUser) { const token = app.jwt.sign({ nickname: data.nickname }, app.config.jwt.secret); ctx.body = { code: 200, msg: '登錄成功', token, roleid: getUser.roleid }; } else { ctx.body = { code: 400, msg: '登錄失敗' }; } } // 獲取所有用戶 async index() { const { ctx } = this; const data = await ctx.service.user.getUser(); ctx.body = { code: 200, msg: '查詢成功', data }; } // 通過id獲取用戶 async show() { const { ctx } = this; const data = await ctx.service.user.getUser(ctx.params.id); ctx.body = { code: 200, msg: '查詢成功', data }; } // 創建用戶 async create() { const { ctx } = this; const { nickname } = ctx.request.body; await ctx.service.user.addUser(nickname); ctx.body = { code: 200, msg: '新增成功' }; } // 修改密碼 async updatePwd() { const { ctx } = this; const { password } = ctx.request.body; await ctx.service.user.editPwd(ctx.params.id, password); ctx.body = { code: 200, msg: '修改成功' }; } } module.exports = UserController;
- package.json
{
"name": "jwt", "version": "1.0.0", "description": "", "private": true, "egg": { "declarations": true }, "dependencies": { "egg": "^2.15.1", "egg-cors": "^2.2.3", "egg-jwt": "^3.1.7", "egg-scripts": "^2.11.0", "egg-sequelize": "^5.2.0", "mysql2": "^2.0.2" }, "devDependencies": { "autod": "^3.0.1", "autod-egg": "^1.1.0", "egg-bin": "^4.11.0", "egg-ci": "^1.11.0", "egg-mock": "^3.21.0", "eslint": "^5.13.0", "eslint-config-egg": "^7.1.0" }, "engines": { "node": ">=10.0.0" }, "scripts": { "start": "egg-scripts start --daemon --title=egg-server-jwt", "stop": "egg-scripts stop --title=egg-server-jwt", "dev": "egg-bin dev", "debug": "egg-bin debug", "test": "npm run lint -- --fix && npm run test-local", "test-local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", "ci": "npm run lint && npm run cov", "autod": "autod" }, "ci": { "version": "10" }, "repository": { "type": "git", "url": "" }, "author": "", "license": "MIT" }
測試
- 登錄
- 查詢
總結
本文主要完成多表的關聯查詢,先通過一個例子,用戶角色之間的關聯完成兩張表之間的查詢,熟悉多表之間的操作。