我正在关注官方的Sequelizer文档,但无法与多个“ hasMany”关联一起使用。
在使用hasMany()
和belongsTo()
关联(通过sequelize,node js和express)时,我只想显示邮递员中的总员工而不是整个项目资源模型
这如何正确完成?
Project.hasMany(projectResource, {foreignKey: 'projectId', sourceKey: 'id'}),
projectResource.belongsTo(Project, {foreignKey: 'projectId', targetKey: 'id'})
many(request)
{
return Project.findAll({
where: request,
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col("projectId")), "totalEmployee"]]
},
include: [
{
model: projectResource
}
],
group: ['Project.id']
})
}
在邮递员中我得到
"project": [
{
"id": 1,
"projectName": "enuke",
"projectManagerId": 2,
"projectType": "2",
"status": "3",
"startDate": "2019-06-18",
"endDate": "2019-06-29",
"createdAt": null,
"updatedAt": "2019-06-19T06:57:57.000Z",
"deletedAt": null,
"totalEmployee": 1,
"projectresources": [
{
"id": 1,
"projectId": 1,
"employeeId": 2,
"createdAt": "2019-06-20T00:00:00.000Z",
"updatedAt": "2019-06-20T00:00:00.000Z",
"deletedAt": null
}
]
}]
答案 0 :(得分:0)
Project.hasMany(projectResource, {foreignKey: 'projectId', sourceKey: 'id'}),
projectResource.belongsTo(Project, {foreignKey: 'projectId', targetKey: 'id'})
many(request)
{
return Project.findAll({
where: request,
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col("projectId")), "totalEmployee"]]
},
include: [
{
model: projectResource,
attributes: [],
}
],
group: ['Project.id']
})
}
你可以试试这个吗