Search code examples
jsonapiposthas-manyloopback

Post to two Tables Loopback


I have a problem with loopback, I want to try to POST to another table. but it can't. here the code that I want to POST to Loopback Explorer at http://localhost:1337/explorer/#!/Order/Order_create

    {
  "Code": "ASDASDASDE",
  "DP": 0,
  "Discount": 0,
  "DiscountNominal": 0,
  "TotalPrice": 0,
  "RequestDate": "string",
  "DeliveryDate": "2017-06-22T07:14:18.815Z",
  "TotalQty": 0,
  "Destination": "string",
  "Phone": "string",
  "Status": "string",
  "PaymentType": "string",
  "DealerCode": "D912839",
  "Active": true,
  "Deleted": true,
  "CreatedBy": "string",
  "CreatedDate": "2017-06-22T07:14:18.815Z",
  "CreateAgent": "string",
  "UpdatedBy": "string",
  "UpdatedDate": "2017-06-22T07:14:18.815Z",
  "UpdateAgent": "string",
  "KioskCode": "A1234",
"orderDetails":[{
  "Code": "ASD123",
  "IsRetur": true,
  "Price": 0,
  "IMEI": "string",
  "Status": "string",
  "OrderCode": "ASDASDASDE",
  "ProductCode": "SM-1923",
  "Active": true,
  "Deleted": true,
  "CreatedBy": "string",
  "CreatedDate": "2017-06-22T07:14:19.045Z",
  "CreateAgent": "string",
  "UpdatedBy": "string",
  "UpdatedDate": "2017-06-22T07:14:19.045Z",
  "UpdateAgent": "string"
}]
}

Let's say, I want to POST to table Order, and table Order detail in the single quote of JSON. the Order Table has been inserted, but the order detail table couldn't.

here my Order.JSON

{
  "name": "Order",
  "plural": "Order",
  "base": "PersistedModel",
  "idInjection": false,
  "options": {
    "validateUpsert": true
  },
  "mixins": {
    "TimeStamp": {}
  },
  "properties": {
    "Code": {
      "type": "string",
      "id": true,
      "required": true
    ....
  },
  "validations": [],
  "relations": {
    "Dealer": {
      "type": "belongsTo",
      "model": "Dealer",
      "foreignKey": "DealerCode"
    },
    "orderDetails": {
      "type": "hasMany",
      "model": "OrderDetail",
      "foreignKey": "OrderCode"
    },
    "Kiosk": {
      "type": "belongsTo",
      "model": "Kiosk",
      "foreignKey": "KioskCode"
    }
  },
  "acls": [],
  "methods": {}
}

here my orderDetail.JSON

{
  "name": "OrderDetail",
  "plural": "orderDetails",
  "base": "PersistedModel",
  "idInjection": false,
  "options": {
    "validateUpsert": true
  },
  "mixins": {
    "TimeStamp": {}
  },
  "properties": {
    "Code": {
      "type": "string",
      "id": true,
      "required": true
    }
.....
  },
  "validations": [],
  "relations": {
    "Order": {
      "type": "belongsTo",
      "model": "Order",
      "foreignKey": "OrderCode"
    },
    "Product": {
      "type": "belongsTo",
      "model": "Product",
      "foreignKey": "ProductCode"
    }
  },
  "acls": [],
  "methods": {}
}

The order has primaryKey: Code and orderDetails has a foreign key: OrderCode that References to Order: Code. what the solution ?? Thanks for helping


Solution

  • you may follow these steps: 1. define a remote method in your order.js file:

    Order.remoteMethod('saveNewOrder', {
        accepts: {arg: 'orderInstance', type: 'json'},
        http: {path:'/order-create', verb:'post'},
        returns: {arg: 'result', type: 'json'}
    });
    

    2. define the saveNewOrder function with the "orderInstance" argument:

    Order.saveNewOrder = function(orderInstance, cb){
        var order = new Order(orderInstance["order"])
        order.save().then(function(savedOrder,err){
        if(err)
            throw err
        else
            savedOrder.orderDetails.create(orderInstance["orderDetails"], function(err, createdOrderDetails){
                if(err)
                    throw err
                else
                    console.log("insertion done:",createdOrderDetails)
            })
        })
    }
    
    1. change your json to match this format:

      {
      "orderInstance":{
          "order":{
              "Code": "ASDASDASDE",
              "DP": 0,
              "Discount": 0,
              ...
          },
          "orderDetails":[{
              "Code": "ASD123",
              "IsRetur": true,
              "Price": 0,
              ...
          }]
          }
      }
      
    2. post your json to http://localhost:3000/api/orders/order-create