所以我有点卡在这里。
我有一个对象,例如:
var lineItems = [
{
id: 1,
quantity: 10
},
{
id: 2,
quantity: 15
},
{
id: 4,
quantity: 22
}
]
现在我需要做的是在 pg-promise SQL 事务中循环,以确保关联 id 的数据库数量中的行项目 >= 对象项目,所以:
SELECT * FROM inventory WHERE id = $1 AND quantity >= $2, [1,10],
SELECT * FROM inventory WHERE id = $1 AND quantity >= $2, [2,15],
SELECT * FROM inventory WHERE id = $1 AND quantity >= $2, [4,22]
如果我收到 3 个结果,则该对象为真,我可以插入请求
INSERT INTO orders SET a = 1, b = 2, c = 3, items = lineItems::json etc RETURNING id;
当然,如果我的结果比 lineItems 对象中的结果少,那么我就不会理会该INSERT
语句,而只需返回一个'item id: 4, quantity:22 doesn't have enough inventory to perform your request...
我最初使用的是:
db.tx(function(t)){
return this.batch([
checkInventory
])
.then(function(inv){
console.log( inv );
});
})
.then(function(results){
console.log( results );
})
.catch(function(error){
console.log( error );
});
checkInventory
我调用的函数在哪里
var checkInventory = function(){
console.log( '|-------------------------------------|' );
console.log( 'LINE ITEMS >> ', lineItems );
var query = [], sql = '';
for( var i = 0; i < lineItems.length; i++ ){
sql += 'SELECT quantity FROM pim_inventory WHERE';
sql += ' product_id = $1 AND quantity >= $2;';
var pquery = [
lineItems[i].id,
lineItems[i].quantity
];
query.push(this.one(sql, pquery));
}
console.log( 'invQUERY >> ', query );
return query;
};
这会产生以下错误:
(node:44810) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): QueryResultError: Multiple rows were not expected.
(node:44810) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): error: syntax error at or near "product_id"
|-------------------------------------|
EVENTS >> [ [ Promise {
<rejected> QueryResultError: Multiple rows were not expected.
at QueryResultError.Error (native)
at new QueryResultError (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg-promise/lib/errors.js:13:22)
at Query.callback (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg-promise/lib/index.js:629:38)
at Query.handleReadyForQuery (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg/lib/query.js:89:10)
at Connection.<anonymous> (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg/lib/client.js:163:19)
at emitOne (events.js:101:20)
at Connection.emit (events.js:188:7)
at Socket.<anonymous> (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg/lib/connection.js:109:12)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7) },
Promise { <rejected> [Object] } ] ]
有任何想法吗?