1、模型中定义关联
三个表:category 分类表 course课程表 user表
在course.js
中定义关联模型关联中引用的字段必须具有唯一性约束
class course extends Model {
static associate(models) {
models.course.belongsTo(models.Category, {
// 自定义外键
foreignKey: 'categorieId'
})
// 默认外键为userId
models.course.belongsTo(models.user)
}
}
在路由中使用
attributes | 是用来指定从数据库表对应的模型中选取哪些字段(属性)出现在查询结果里的配置项 |
---|---|
exclude | 从查询结果中排除的字段 |
include | 用于处理模型之间的关联关系查询 |
model | 关联的模型 |
as | 别名 |
attributes | 同上述 |
// 引入相关模型
const {course, Category, user} = require("../../models");
const condition = {
attributes: {
exclude: ['categorieId', 'userId']
},
include: [{
model: Category,
as: 'category',
attributes: ['id', 'name']
}, {
model: User,
as: 'user',
attributes: ['id', 'username', 'avatar']
}],
order: [["id", "desc"]],
limit: pageSize, // limit 显示数量
offset, // 从第几个索引开始
};