我需要创建一个 shopify 订单数据库,以便我可以运行在 shopify 管理区域中无法执行的高级查询和销售报告。我正在构建 Sails .12 和 mysql。 Shopify 允许您注册一个 webhook,这样每次下订单时,它都会创建一个 POST 到指定的 URL,正文中的订单数据为 JSON。订购的产品是一个 JSON 对象数组,作为 POST 中的值之一:
{
"id": 123456,
"email": "jon@doe.ca",
"created_at": "2017-01-10T14:26:25-05:00",
...//many more entires
"line_items": [
{
"id": 24361829895,
"variant_id": 12345,
"title": "T-Shirt",
"quantity": 1,
"price": "140.00",
},
{
"id": 44361829895,
"variant_id": 42345,
"title": "Hat",
"quantity": 1,
"price": "40.00",
},
]
}
我需要将订单保存到一个 Orders 表中,并将订购的产品保存到一个一对多关系的 line_items 表中;一个订单可以有多个 line_items(订购的产品)。 Webhook 发送了 100 多个键值对,我正在保存所有这些。我已经在定义数据类型的地方创建了两个模型,所以现在我有很长的 Order.js 和 Line_item.js 文件,并且我正在使用
line_items: {
collection: 'line_item',
via: 'order_id'
},
在我的 Order.js 中,和
order_id: {
model: 'order'
},
在我的 Line_item.js 模型中关联它们。这是定义我的两个表的正确方法吗?另外,我应该把将 JSON 映射到模型参数的代码放在哪里?如果我将该代码放入 Controller 中,我是否必须再输入 100 多行代码才能将每个 json 值映射到其正确的参数。我将如何保存到两个不同的模型/表?例如:
var newOrder = {};
newOrder.id =req.param('id');
newOrder.email = req.param('email');
newOrder.name = req.param('name');
...//over 100 lines more, then Order.create(newOrder, ...)
var newLine_items = req.params('line_items'); //an array
_.forEach(newLine_items, function(line_item){
var newLine_item = {};
newLine_item.id = line_item.id;
newLine_item.order_id = newOrder.id;
newLine_item.title = line_item.title;
//etc for over 20 more lines, then Line_item.create(newLine_item, ...)
});
最佳答案
我需要将订单保存到一个 Orders 表中,并将订购的产品保存到一个一对多关系的 line_items 表中;一个订单可以有多个 line_items(订购的产品)。
这听起来完全合理,嗯,除了使用牛津逗号 :)
webhook 发送了 100 多个键值对
我不确定我是否完全理解这是什么或它在此过程中的用途。
也就是说,在您的模型中为此设置一个具有 JSON 值的属性可能会有所帮助,然后检索它并将其作为 JSON 使用,而不是尝试手动说明每个属性(如果您是这样的话)那边干什么?
这实际上取决于您的用例以及您将如何使用数据,但我认为如果格式发生变化您可能会遇到问题,如果它只是作为 JSON 对象存储和解析则不是这样?
另外,我应该把将 JSON 映射到模型参数的代码放在哪里
在 v0.12.x 中查看 Services .
在 v1 中,服务仍然可以工作,但将此逻辑移至 Helpers可能是一个不错的选择,但似乎 custom model method会更好。
这是您的代码的较短版本:
var newOrder = req.allParams();
newLine_items = {};
_.forEach(newOrder.line_items, function(line_item) {
newLine_items.push(line_item);
});
您的逻辑可能如下所示:
var newOrder = req.allParams();
// Store the order
Order
.create(newOrders)
.exec(function (err, result) {
if (err) // handle the error
var newLine_items = {};
_.forEach(newOrder.line_items, function(line_item) {
// Add the order id for association
line_item.order_id = result.id;
// Add the new line item with the orders id
newLine_items.push(line_item);
});
// Store the orders line items
LineItems
.create(newLine_items)
.exec(function (err, result) {
if (err) // handle the error
// Handle success
});
});
Order 模型中的生命周期回调:
beforeCreate: function (values, cb) {
delete(values.line_items);
cb();
}
但是你真的应该研究一下 bluebird promises,因为第一版 sails 中的模型方法已经选择支持它们,它有助于否定在我的示例中开始的厄运金字塔,这也是你想要避免的事情:P
关于mysql - Sailsjs MVC 将参数从外部 API 映射到多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601276/