Can't save empty string into field value

2019-09-01 09:26发布

问题:

I need to change value of NULL-field to empty string (in sales_flat_order table). I tried this code:

$orders = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToFilter('created_at', array('to' => $endDate))
    ->addAttributeToFilter('status', array('eq' => Mage_Sales_Model_Order::STATE_COMPLETE));

foreach ($orders as $order) {
    $comment  = $order->getCustomerNote();
    if (is_null($comment)) {
        $order->setData('customer_note', '');
        try {
            $order->save();
        } catch (Exception $e){
            echo $e->getMessage();  exit;
        }
    }
}

But in base I see still NULL value in this filed. If I change empty string to any non-empty it works fine. How can I update NULL value field to empty string?

Thanks.

回答1:

The empty string is set to null in Varien_Db_Adapter_Pdo_Mysql::prepareColumnValue():

case 'varchar':
case 'mediumtext':
case 'text':
case 'longtext':
    $value  = (string)$value;
    if ($column['NULLABLE'] && $value == '') {
        $value = null;
    }
    break;

To reset the column value to empty string, add this in your resource model:

protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
{
    $data = parent::_prepareDataForSave($object);
    if ($object->getData('your_column_name') === '') {
        $data['your_column_name'] = '';
    }
    return $data;
}


回答2:

I tried and it's normal.

              $order->setData('customer_note', new Zend_Db_Expr(''));
              try {
                       $order->save();
                } catch (Exception $e){
                      echo $e->getMessage();  exit;
                }


标签: magento