【发布时间】:2017-05-26 20:35:15
【问题描述】:
我需要创建一个 shopify 订单数据库,以便我可以运行在 shopify 管理区域中无法执行的高级查询和销售报告。我在 Sails .12 和 mysql 中构建。 Shopify 允许您注册一个 webhook,以便每次下订单时,它都会创建一个指向指定 URL 的 POST,其中包含 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 映射到模型参数的代码放在哪里?如果我将该代码放入控制器中,我是否必须再键入 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, ...)
});
【问题讨论】:
标签: mysql node.js model-view-controller sails.js waterline