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:
So instead of this:
I now do this:
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.