Egg中使用Sequelize ORM框架操作MySQL--關聯(lián)查詢
只需在定義model的時候,加入tableName字段即可。
module.exports = app => { const { STRING, INTEGER, DATE } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, username: STRING(30), age: INTEGER, sex: STRING(30), created_at: DATE, updated_at: DATE, },{ tableName: "usera" }); return User;};復制代碼
設置不顯示createdAt等時間戳字段
{ tableName: "usera", timestamps: false}復制代碼
注意:如果數(shù)據(jù)庫中使用的是下劃線命名法,在model中需要使用駝峰命名法。
article表的結構
article的model
'use strict';module.exports = app => { const { STRING, INTEGER, DATE } = app.Sequelize; const Article = app.model.define('article', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, title: STRING(255), description: STRING(255), cateId: INTEGER, state: INTEGER },{ tableName: "article", timestamps: false }); // 實現(xiàn)關聯(lián)的核心代碼是下面的語句 Article.associate = function() { // 1對1 app.model.Article.belongsTo(app.model.ArticleCate,{foreignKey: 'cateId'}); } return Article;};復制代碼
article_cate的model
'use strict';module.exports = app => { const { STRING, INTEGER, DATE } = app.Sequelize; const ArticleCate = app.model.define('article_cate', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, title: STRING(255), state: INTEGER },{ tableName: "article_cate", timestamps: false }); return ArticleCate;};復制代碼
一對一查詢方法
async onevsone() { const result = await this.ctx.model.Article.findAll({ include: { model: this.ctx.model.ArticleCate } }); this.ctx.body = result; }復制代碼
查詢到的結果如下圖所示:
article_cate.js
ArticleCate.associate = function () { // 1對1 app.model.ArticleCate.hasMany(app.model.Article, { foreignKey: 'cateId' }); }復制代碼
路由
async onevsmany() { const result = await this.ctx.model.ArticleCate.findAll({ include: { model: this.ctx.model.Article } }); this.ctx.body = result; }復制代碼
多對多查詢主要是使用belongsToMany。
一門課程可以被多個學生選修
Lesson.associate = function(){//一個課程可以被多個學生選修 app.model.Lesson.belongsToMany(app.model.Student, { through: app.model.LessonStudent, foreignKey: 'lessonId', otherKey: 'studentId' });}復制代碼
一個學生可以選修多門課程(代碼中的through指的是中間表)
Student.associate = function (){ //一個學生可以選修多門課程 app.model.Student.belongsToMany(app.model.Lesson, { through: app.model.LessonStudent, foreignKey: 'studentId', //注意寫法 otherKey: 'lessonId' });}復制代碼
查詢語句
const { ctx } = this;let result = await ctx.model.Student.findAll({ include: { model: ctx.model.Lesson }});
版權聲明:本文內容轉發(fā)自阿里云社區(qū),由阿里云實名注冊用戶自發(fā)貢獻!版權歸原作者所有。本站不擁有其著作權,亦不承擔相應法律責任。如果您發(fā)現(xiàn)本文中有涉嫌抄襲的內容,請聯(lián)系站內客服,本站將立刻刪除涉嫌侵權內容。
一、Sequelize自定義表名
使用Sequelize實現(xiàn)多表查詢
一對一查詢
一對多查詢
多對多查詢