I am doing some raw query binding in objectionjs and my code is as follows:
const item = await cart.$relatedQuery('items').insert(req.body)
.onConflict(['cartId', 'productId'])
.merge({
amount: raw('cart_item.amount + ?', req.body.amount),
price: raw('cart_item.price + ?', req.body.price)
});
Values for req.body.amount
and req.body.price
can be both positive and negative. Because of this, at some point the final value for amount
and price
fields in the database might become negative too after the addition/subtraction. And I want to prevent that from happening. What should I do in such case?
I tried the following:
amount: Math.max(raw('cart_item.amount + ?', req.body.amount), 0)
But this doesn't work (of course it shouldn't) and returns NaN. I don't want to put an .unsigned()
check on the field itself, but check during runtime. Is there any way I can get what I want without making multiple queries to fetch the values for amount
and price
beforehand and checking before inserting the new values?