我遇到环回问题,我想尝试POST到另一个表。但它不能。这里是我要POST到Loopback Explorer的代码 在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"
}]
}
让我们说,我想POST到表Order,并在JSON的单引号中列出Order详细信息。已插入订单表,但订单明细表不能。
这里是我的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": {}
}
这里是我的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": {}
}
订单有primaryKey:Code和orderDetails有一个外键:OrderCode引用Order:Code。什么解决方案?谢谢你的帮助
答案 0 :(得分:0)
您可以按照以下步骤操作: 1.在order.js文件中定义一个远程方法:
Order.remoteMethod('saveNewOrder', {
accepts: {arg: 'orderInstance', type: 'json'},
http: {path:'/order-create', verb:'post'},
returns: {arg: 'result', type: 'json'}
});
2。使用“orderInstance”参数定义saveNewOrder函数:
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)
})
})
}
更改您的json以匹配此格式:
{
"orderInstance":{
"order":{
"Code": "ASDASDASDE",
"DP": 0,
"Discount": 0,
...
},
"orderDetails":[{
"Code": "ASD123",
"IsRetur": true,
"Price": 0,
...
}]
}
}