0

How I can make a initial load data in a hasAndBelongsToMany relation ?

Example:

Model Product
{
idProduct,
Description
(..)
}

Model Order
{
idOrder,
Date
(...)
}

In the swagger have:

PUT: /order/{id}/product/rel/{fk}
{
  "id": "string",
  "orderId": "string",
  "productId": "string"
}

But in I dont know how I can make this my node boot script (how method I can call to make this) ...

I know how to insert orders, insert products but I dont know how I can "link" one or more products in one or more orders.

I see in other links the "Order.Product.link({id1: val1, id2: val2})" but dont work in node...

il_raffa
  • 5,090
  • 129
  • 31
  • 36
Celso Cruz
  • 3
  • 1
  • 1

1 Answers1

0

To create a new link, you need to obtain an instance of the source model (Order) first, and then call relation method add to establish the relation with the target model (Product).

const order = await Order.findById(orderId);
await order.products.add(productId);

If you are adding products while creating a new order:

const order = await Order.create({/* order data */});
await order.products.add(productId);

Here is a callback based version in case you are not using async functions or Promises yet:

Order.findById(orderId, function(err, order) {
  if (err) // handle the error

  order.products.add(productId, function(err) {

    if (err) // handle the error
    // done
  });
});
Miroslav Bajtoš
  • 10,667
  • 1
  • 41
  • 99