2013-04-14 158 views
8

我一直在編寫一個更新我的屬性add_ten_pence的腳本,該屬性是一個yes/no布爾值。目前它經歷了數據庫中的SKU's,但不幸的是它沒有更新數據庫。我已經粘貼下面的腳本有誰知道我要去哪裏錯了?以編程方式更新Magento屬性

該屬性默認設置爲「否」,並且我希望在腳本運行時將其更改爲「是」,反之亦然。

require_once('app/Mage.php'); 

umask(0); 
Mage::app('default'); 
Mage :: app()->setCurrentStore(Mage_Core_Model_App :: ADMIN_STORE_ID); 
$productCollection = Mage::getModel('catalog/product')->getCollection(); 

foreach($productCollection as $_product) 
{ 
    echo "\n".'updating '.$_product->getSku()."...\n"; 
    $product = Mage::getModel('catalog/product')->load($_product->getEntityId()); 
    $product->setAddTenPence(true); 
    $product->save(); 
} 

回答

25

嘗試保存單個屬性而不是整個產品集合。

require_once('app/Mage.php'); 

umask(0); 
Mage::app('default'); 
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); 
$productCollection = Mage::getModel('catalog/product')->getCollection(); 

foreach($productCollection as $_product) 
{ 
    echo "\n".'updating '.$_product->getSku()."...\n"; 
    $_product->setData('add_ten_pence', 1)->getResource()->saveAttribute($_product, 'add_ten_pence'); 
} 

UPDATE

更快的方法:

$productCollection = Mage::getModel('catalog/product')->getCollection(); 
$array_product = $productCollection->getAllIds();  
Mage::getSingleton('catalog/product_action')>updateAttributes($array_product, array('add_ten_pence' => 1), Mage_Core_Model_App::ADMIN_STORE_ID); 

(感謝https://magento.stackexchange.com/users/146/marius!)

+0

優秀,感謝您的幫助! – iamgraeme

+1

當我把這個片段Mage :: app() - > setCurrentStore(Mage_Core_Model_App :: ADMIN_STORE_ID);它適用於我,因爲在區域前端執行代碼時,如果您的控制器是admin,則不需要設置ADMIN_STORE_ID。 – jruzafa

+0

謝謝,這優化了我的節省時間。順便說一句:我通常在哪裏找到對象上的所有可用方法?沒有Magento的文檔可以幫助解決這個問題。 – Alan

相關問題