MySQL – Always Update on Duplicate When Using Save() in Custom Model

magento-1.9modelMySQLresource-model

I have a custom model linked to a custom table. In that table, the column sku is unique. I'd like the following code to always update on duplicate:

Mage::getModel('company/product_log')
  ->setData('sku', 'abc123')
  ->setData('error', 'Invalid price.')
  ->save();

I'd like to do this from within the model itself instead of having to repeat update-vs-insert logic everywhere I want to use this table.

What is the best way to do this, or an existing example already in Magento?

Best Answer

The method that I came up which seems to work fine is to add this method to my model:

/**
 * @param $sku
 * @return $this|Mage_Core_Model_Abstract
 */
public function loadBySku($sku) {
    $matches = $this->getResourceCollection()
        ->addFieldToFilter('sku', $sku);

    foreach ($matches as $match) {
        return $this->load($match->getId());
    }

    return $this->setData('sku', $sku);
}

So instead of this:

Mage::getModel('company/product_log')
  ->setData('sku', 'abc123')
  ->setData('error', 'Invalid price.')
  ->save();

I now do this:

Mage::getModel('company/product_log')
  ->loadBySku('abc123')
  ->setData('error', 'Invalid price.')
  ->save();

If a row exists with that SKU, it will be loaded, altered and saved. If a row doesn't exist with that SKU, the blank model will have it's SKU set, and then have the error set and the row saved.

loadBySku() could be altered to include more default values when it can't load an existing row by SKU.

Related Topic