magento update crossell product programmly

2210 ワード

<?php 
class Bysoft_Import_Model_Crosssells extends Mage_Core_Model_Abstract {
	protected $_store_id;
	public function  get_store_by_code($storeCode) {
		$stores = array_keys(Mage::app()->getStores());
		foreach($stores as $id){
			$store = Mage::app()->getStore($id);
			if($store->getCode()==$storeCode) {
				return $store;
			}
		}
		return null; // if not found
	}
	public function run() {
		//get all products in en-storeview
		$this->_store_id = $this->get_store_by_code('english')->getId();// english or tr_cn
		$collection = Mage::getModel('catalog/product')->getCollection();
		foreach ($collection as $_product) {
			$_product = Mage::getModel('catalog/product')->load($_product->getId())->setStoreId($this->_store_id);
			if (trim($_product->getName())) {
				$crosssells_param = $this->get_crosssells_param($_product->getId(),$_product->getName());
				$product = Mage::getModel('catalog/product')->load($_product->getId());
				$product->setCrossSellLinkData($crosssells_param);
				$product->save();
				var_dump($product->getId() . ' Crossell products:');
				var_dump($crosssells_param);
			}
		}
	}
	
	public function get_crosssells_param($except_id, $name) {
		$param = array();
		$collection = Mage::getResourceModel('catalog/product_collection')
                  ->addAttributeToSelect('*')
                  ->addAttributeToFilter('name', array('eq' => $name))
                  ->addAttributeToFilter('entity_id', array('neq' => $except_id))
   				 ->setOrder('entity_id','asc')
                  ->load();
		
		$position = 0;
		
		foreach ($collection as $_product) {
			$param[$_product->getId()] = array('position'=>$position);
			++$position;
		}
		
		return $param;
	}
	
	
}
?>