user_list用户表、project_list项目表、user_project_mid用户-项目关联表
//建立关联关系
// 与ProjectList存在多对多关系,使用belongsToMany() 中间表为UserProjectMid
app.model.UserList.belongsToMany(app.model.ProjectList, {
through: app.model.UserProjectMid,
foreignKey: 'userName', //关联表的userName
sourceKey:'userName', //通过ProjectList表的userName与关联表关联,如果不设置默认与主键关联
otherKey: 'projectId'
});
// 与UserList存在多对多关系,使用belongsToMany() 中间表为UserProjectMid
app.model.ProjectList.belongsToMany(app.model.UserList, {
through: app.model.UserProjectMid,
foreignKey: 'projectId', //关联表的userName
otherKey: 'userName'
});
//查询当前用户下的所有项目
async getProject(params) {
const { app } = this;
let { userName } = params
let data = await app.model.ProjectList.findAll({
include: [{
model: app.model.UserList,
where: {
userName //筛选当前用户
},
attributes: [] //舍弃用户信息的内容
}]
})
return data
}
//获取项目所有成员
async getProjectTeam(params) {
const { app } = this;
let { projectId } = params
let data = await app.model.UserList.findAll({
attributes: [Sequelize.col('project_lists.user_project_mid.level'),'avatar','nickname','userName'], //数据打平后要输出的zi段
include: [{ //关联查询选项
model: app.model.ProjectList,
where: {
id:projectId
},
through: { attributes: [] }, //筛选中间表字段
attributes: [] //筛选关联表字段
}],
raw: true, //数据打平属性
})
return data
}