How to return just created row with its association with sequelize

Question

with the create() method I get the just created row back is there a way to get its associations also back.

like the include option we get with findAll

for example I have this output on create

~~~text
~~~text
{
    "id": 62,
    "product_id": 1, // Association
    "quantity": "20",
    "user_id": 1,  // Association
    "updatedAt": "2021-06-04T12:20:33.370Z",
    "createdAt": "2021-06-04T12:20:33.370Z"
  }

Answer

At the moment, to achieve this simply run a second query to retrieve the newly created object like below:

`Order.create({
      productId,
      quantity,
      userId
    }).then((newOrder) => {
      Order.findAll({
        where: { orderId: newOrder.orderId },
        include: [
          {
            model: Product //association
          },
          {
            model: User //association
          }
        ]
      }).then((order) => {
        console.log('new order', order);
      });
    });`

If there is anyone that knows of a better way to retrieve the newly created object, i would also appreciate the solution.

This answer was originally posted on Stack Overflow. You can find the full discussion here

Related Posts

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

## Question Can one transfer repositories from GitLab to GitHub if the need be. If so, how exactly can I go about doing the same? Also, are there any pitfalls in doing so or precautionary measures

Read More

Cannot set headers after they are sent to the client - error

## Question Error `[ERR_HTTP_HEADERS_SENT]`: Cannot set headers after they are sent to the client ```text `at ServerResponse.setHeader (_http_outgoing.js:558:11) at ServerResponse.header (D:\D

Read More

Pulling data with 'Where' and 'Include' statements at the same time

## Question I have managed to get my include statements working with my foreign keys however when I try to add a 'where' statement to the findAll statement I am getting the below error. I have check

Read More