Decrement value instead of setting it like `number = number - 1`. Is it possible in Magento?
-
12-12-2019 - |
سؤال
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?
المحلول
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.
نصائح أخرى
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.