我正在制作一个示例捐赠应用程序,我想获取用户所做的所有捐赠,以及捐赠也已关联的原因。
exports.getUserDonations = (req, res) => {
// Get Donations made by the user by userID
Donation.findAll({
where: {
userID: req.params.id,
},
attributes: ['amount', 'updatedAt', 'causeID'],
include: [{
model: Cause,
as: 'Causes',
}]
})
.then(donations => {
if (donations) {
res.status(200).json(donations);
} else {
res.status(404).send({ error: "No Donations found" });
}
})
.catch(err => {
console.log("Error: ", err)
res.status(500).json(err);
});
}
由于某种原因,我得到了这种结果。如您所见,“ causeID”(12)和“ Cause.id”(17)字段不匹配。我的想法是上面的where语句可能覆盖了某些内容。
{
"amount": 82,
"updatedAt": "2018-11-02T17:04:30.847Z",
"causeID": 12,
"Causes": {
"id": 17,
"userID": 1,
"orgID": null,
"name": "Croation Trip",
"type": "Trip",
"amount": 3000,
"description": "Just taking a trip",
"purpose": "Food, sun, and fun",
"createdAt": "2018-09-20T21:56:37.330Z",
"updatedAt": "2018-09-20T21:56:37.330Z"
}
},
// Most fo the time the cause comes back as null
{
"amount": 10,
"updatedAt": "2018-11-27T01:35:06.061Z",
"causeID": 13,
"Causes": null
},
这是我与每个人的关联
// Cause association
Cause.associate = function(models) {
Cause.belongsTo(models.User, {
as: "Users",
foreignKey: "id"
})
Cause.hasMany(models.Donation, {
as: "Donations",
foreignKey: "causeID"
})
};
// Donation associations
Donation.associate = function(models) {
Donation.belongsTo(models.Cause, {
as: "Causes",
foreignKey: "id"
})
Donation.belongsTo(models.User, {
as: "Users",
foreignKey: "id"
})
};
答案 0 :(得分:0)
好像您不匹配某些键。我认为您的示例将Donation.Id加入到Cause.Id中-您应该通过查看生成的SQL进行确认。将密钥与不同名称关联的方法如下:
Donation.belongsTo(models.Cause, {
as: "Causes",
{foreignKey: "id", sourceKey: "causeId"}
})
或使用更多捐赠属性进行测试:
attributes: ['id', 'userId', 'amount', 'updatedAt', 'causeID'],
捐赠ID是否与原因ID相符?