Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize - How to set association, save entity and return the saved entity with the associated entity

I am trying to create an association between an existing (user) entity and save the new entity (visit).

I've read the sequelize docs and can't see a better way of doing this than saving the first entity using async/await, then fetching it again passing include as an option. See below.

export const createVisit = async(req, res) => {
  req.assert('BusinessId', 'Must pass businessId').notEmpty();
  req.assert('UserId', 'Must pass customerId').notEmpty();

  const visit = await new Visit({
    UserId: req.body.UserId,
    BusinessId: req.body.BusinessId,
    redemption: false,
  })
  .save()
   .catch((error) => {
    res.status(400).send({ error });
  });

    const visitWithUser = await Visit.findById(visit.id, {include: [{model: User, attributes: ['firstName','lastName','facebook', 'gender','email']}]})

    res.status(200).send({ visit: visitWithUser })
};

Is there a way to save the entity and get sequelize to return the saved entity along with any associations?

like image 423
Powderham Avatar asked Jan 26 '26 12:01

Powderham


1 Answers

I think it supports this feature , as per the doc , you can do it like this :

Visit.create({
    UserId: req.body.UserId,
    BusinessId: req.body.BusinessId,
    redemption: false,
}, {
  include: [User]
}).then(function(comment) {
    console.log(comment.user.id);
});

Here is the git discussion if you want to read.

like image 140
Vivek Doshi Avatar answered Jan 29 '26 06:01

Vivek Doshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!