I had to look into this issue and found the problem. The whole stock data/item interface is a bit tricky.
Problem
Mage_Catalog_Model_Abstract->loadByAttribute
uses collection-loading on collection catalog/product_collection
with a limit of 1.
Stock items of products in that collection are loaded via the event observer Mage_CatalogInventory_Model_Observer->addStockStatusToCollection
which listens to event catalog_product_collection_load_after
. addStockStatusToCollection
loads stock items of products only if flag require_stock_items
is set true
.
In case of Mage_Catalog_Model_Abstract->loadByAttribute
this flag isn't set so we end up with $product->_data['stock_item']
being of type Varien_Object
(see Mage_CatalogInventory_Model_Stock_Status
lines 488-491).
This causes error
Invalid method Varien_Object::save...
on $product->save
.
I recommend solution 1 if you save the product anyway and want the stock update to happen in the same transaction. Solution 2 only sets stock data so it avoids calling expensive $product->save
.
Solution 1
Use an additional load on the product: this loads $product->_data['stock_item']
properly.
Mage::getModel('catalog/product')->loadByAttribute('sku', 62701 );
$tempProduct->load($tempProduct->getId());
This is an additonal read transaction on the database which slows things down.
Solution 2
As in other answers suggested use the class Mage_CatalogInventory_Model_Stock_Item
directly. But you have reference the product correctly via call to setProduct
to have working code both for new and existing stock items.
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
$stockItem->setProduct($product)
->setData('stock_id', Mage_CatalogInventory_Model_Stock::DEFAULT_STOCK_ID)
->setData('qty', 1)
->setData('is_in_stock', 1)
->setData('manage_stock', 1)
->setData('use_config_manage_stock', 0)
->setData('use_config_backorders', 0)
->setData('backorders', 0)
->setData('use_config_max_sale_qty', 0)
->setData('max_sale_qty', 1)
->save();