如何使用Sequelize在PostgreSql中仅获取插入的数据?

3

我希望在将用户添加到“WOD”表后获取更新的表值。例如,我的WOD表中有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);
  }
};
1个回答

3
由于多对多关联,sequelize.sync将为我们生成一些functions。您使用了addParticipants函数,它返回一个添加到关联表(userwod)的数组。
在这个数组中,您会发现一些id字段(连接表字段),因为您只是像这样运行INSERT INTO 'user_wods' ('user_id''wod_id') VALUES (2,1)。如果您想返回添加的用户信息,则应运行SELECT * FROM 'user' WHERE 'id'=2
您必须调用reload函数来获取第三个人。
await wod.reload()

1
非常感谢,伙计。我之前不知道reload方法。它可以更新对象而不创建另一个对象。 - Çağatay Sert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接