Magento – Difference between $product->getResource()->save($product); $product->save();

magento-1.9product

Can anyone know what is the difference between use of

$product->getResource()->save($product);

$product->save();

Best Answer

There is not a huge difference. When calling save directly from the product object, that function also calls $product->getResource()->save($product).

However, both the product model and product resource model can have beforeSave() and afterSave() events. So when you call $product->getResource()->save($product), you end up skipping the beforeSave/afterSave events that exist within the main product model and only those that exist within the resource model are called.

The main difference between the two, is that when calling $product->save(), it calls Mage_Catalog_Model_Product::_beforeSave() which contains this logic:

/**
 * Check product options and type options and save them, too
 */
protected function _beforeSave()
{
    $this->cleanCache();
    $this->setTypeHasOptions(false);
    $this->setTypeHasRequiredOptions(false);

    $this->getTypeInstance(true)->beforeSave($this);

    $hasOptions         = false;
    $hasRequiredOptions = false;

    /**
     * $this->_canAffectOptions - set by type instance only
     * $this->getCanSaveCustomOptions() - set either in controller when "Custom Options" ajax tab is loaded,
     * or in type instance as well
     */
    $this->canAffectOptions($this->_canAffectOptions && $this->getCanSaveCustomOptions());
    if ($this->getCanSaveCustomOptions()) {
        $options = $this->getProductOptions();
        if (is_array($options)) {
            $this->setIsCustomOptionChanged(true);
            foreach ($this->getProductOptions() as $option) {
                $this->getOptionInstance()->addOption($option);
                if ((!isset($option['is_delete'])) || $option['is_delete'] != '1') {
                    $hasOptions = true;
                }
            }
            foreach ($this->getOptionInstance()->getOptions() as $option) {
                if ($option['is_require'] == '1') {
                    $hasRequiredOptions = true;
                    break;
                }
            }
        }
    }

After this runs, the same $this->getResource()->save($this) is called.

Related Topic