将用户添加到“ WOD”表后,我想获取更新的表值。例如,我的WOD表中有2个用户,添加第三个用户后,我想返回响应给客户端,因为我刚刚插入了数据(第三个家伙)。但是现在,我只能返回前2个用户,因为我不能获取更新的值。当然,插入后我可以进行另一个查询以获取更新的表值,但是还有更好的解决方案吗?这是我的代码;
const addUser = async (req, res) => {
try {
const { userId, wodId } = req.body;
if (!userId || !wodId) {
res.status(400).send({ status: false, message: 'need userId and wodId' });
}
const wod = await Wod.findByPk(wodId, {
include: [
{
model: User,
as: 'Participants',
through: { attributes: [] }
}
]
});
//check capacity if full.
if (wod.Participants.length >= wod.capacity) {
res
.status(403)
.send({ status: false, message: 'Capacity of this class is full!' });
}
const result = await wod.addParticipants(userId);
res.status(201).json({ status: !!result, wod });
} catch (error) {
res.status(500).send({ status: result, message: error.message });
console.log(error.message);
}
};
由于多对多关联,sequelize.sync将为我们生成一些功能。您使用了addParticipants函数,这将返回一个添加到assocation(userwod)表中的数组。
在此数组中,您将找到一些id字段(联接表字段),因为您只是这样运行INSERT INTO 'user_wods' ('user_id''wod_id') VALUES (2,1)
。如果要返回添加的用户信息,则应运行SELECT * FROM 'user' WHERE 'id'=2
。
您必须调用reload函数来获取第三个家伙。
await wod.reload()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句