Creative in a loop

I have an order model that has Many OrderItem models. But as soon as the client wants to create an Order, he must first create an Order object, and then for each product that he added to his cart, he needs to create individual OrderItems. As you can see, this causes a lot of retry requests. Can I create my own method for OrderItems that uses a list of products. But I was wondering if there is a built-in mechanism to do this, like createMany, as it is a very useful operation.

ORDER MODEL

 {
  "name": "Order",
  "plural": "Orders",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "customerId": {
      "type": "number",
      "required": true
    },
    "branchId": {
      "type": "number",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "orderItems": {
      "type": "hasMany",
      "model": "OrderItem",
      "foreignKey": "orderId"
    }
  },
  "acls": [],
  "methods": []
}

      

MODEL ORDERITEM

{
  "name": "OrderItem",
  "plural": "OrderItems",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "UnitPrice": {
      "type": "number"
    },
    "productId": {
      "type": "number",
      "required": true
    },
    "purchaseOrderId": {
      "type": "number",
      "required": true
    },
    "quantity": {
      "type": "number"
    }
  },
  "validations": [],
  "relations": {
    "product": {
      "type": "belongsTo",
      "model": "Product",
      "foreignKey": "productId"
    },
    "purchaseOrder": {
      "type": "belongsTo",
      "model": "PurchaseOrder",
      "foreignKey": ""
    }

  },
  "acls": [],
  "methods": []
}

      

+3


source to share


1 answer


The "create" loopback method also accepts an array of objects (see the PersistedModel.create docs), so you should try to create one "create" call and send the OrderItems array.



+4


source







All Articles