2021-11-17 198
这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战
只需在定义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; }; 复制代码
{ tableName: "usera", timestamps: false } 复制代码
注意:如果数据库中使用的是下划线命名法,在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 }); // 实现关联的核心代码是下面的语句 Article.associate = function() { // 1对1 app.model.Article.belongsTo(app.model.ArticleCate,{foreignKey: 'cateId'}); } return Article; }; 复制代码
'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; } 复制代码
查询到的结果如下图所示:
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' }); } 复制代码
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 } });
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。