8

I need to decrement a value with an atomic database operation, is it possible using Magento models?

setNumber($number) works like number = $number, but I need it to be decremented in SQL query.

Is it possible in Magento or do I have to write the SQL query myself?

Fabian Schmengler
  • 65,791
  • 25
  • 187
  • 421
tmm
  • 359
  • 1
  • 9
  • 4
    I'm voting to close this question as off-topic because it is about MYSQL – Sander Mangel Feb 17 '15 at 13:55
  • 2
    @Sander-MageStackDay2015 It's not about MYSQL, I am asking if there is a Magento function that instead of setNumber(number) has something like decreaseBy(number) – tmm Feb 17 '15 at 13:58

2 Answers2

16

Yes, it's possible, using Zend_Db_Expr:

$object->setNumber(new Zend_Db_Expr('number-1'));

For reference:

The method Mage_Core_Model_Resource_Abstract::_prepareDataForSave() contains the following code:

if ($object->hasData($field)) {
    $fieldValue = $object->getData($field);
    if ($fieldValue instanceof Zend_Db_Expr) {
        $data[$field] = $fieldValue;
    } else {
        ... [normal value processing follows]

EAV Models:

Note that you only can reference the attribute by its name ("number" in the example) if it's a real column of the main table, not an EAV attribute.

Although the abovementioned method is only used by models with flat tables, Zend_Db_Expr can be used for EAV attributes as well, the method that handles it is Varien_Db_Adapter_Pdo_Mysql::prepareColumnValue().

BUT you always have use the column name "value":

$product->setNumber(new Zend_Db_Expr('value-1'));

You don't need to specify a table alias because during save each attribute gets processed with its own query, so "value" is not ambiguous.

Fabian Schmengler
  • 65,791
  • 25
  • 187
  • 421
0
try ->setNumber(getNumber() - $number)

Edit: This would be equivalent of Set number = number - X in mysql where X is $number.

If you want to do it in MySQL only then you just need to write a query.

Paras Sood
  • 2,540
  • 1
  • 14
  • 23