Add Relation Product From a table

Here is the table content:

id	skus
1	P763B,P763A,P739A,P574P,P574C,P574B,P573K
2	P573G,P0870,P0860,D9543,D8984
3	D8983,D8821,D8579,D8573,D853A,D8539
4	D824A,D7805

 Add each sku with its relation product skus(in one line) into magento

<?php
/**
 * 导入关联商品
 * @author bysoft
 *
 */
class Bysoft_Import_Model_Relationproduct extends Mage_Core_Model_Abstract
{
	protected $_write;
	protected $_read;
	
    protected function _construct(){

       $this->_init("import/relationproduct");
       $this->_read = Mage::getSingleton('core/resource')->getConnection('core_read');
       $this->_write = Mage::getSingleton('core/resource')->getConnection('core_write');

    }
    
    public function run() {
    	//Follow four should run only no data in temp tables.
    	$this->truncate_table();//clean product data table;
    	$this->import_data_from_csv_to_db();//get product data from csv file
    	$this->add_relation_products();
    }
    
    public function truncate_table() {
    	$sql = "truncate table bysoft_import_relation_product";
    	$this->_write->query($sql);
    }
    
    public function import_data_from_csv_to_db() {
    	$file_path = BP . DS . 'media' . DS . 'import' . DS . 'relation_product.csv';
    	$file = fopen($file_path,'r');
    	$i = 0;
    	while ($data = fgetcsv($file)) {
    		++$i;
    		if ($i != 1) {
    			$model = Mage::getModel('import/relationproduct');
    			$skus = str_replace(' ','',$data[0]);
    			$skus = str_replace(',',',',$skus);
    			$model->setData('skus',$skus);
    			$model->save();
    			var_dump($data[0]  . ' save into db.');
    		}
    	}
    }
    
    public function add_relation_products() {
    	$sql = "select skus from bysoft_import_relation_product order by id";
    	$results = $this->_read->fetchAll($sql);
    	foreach ($results as $row) {
    		$skus = trim($row['skus']);
    		$sku_arr = explode(',', $skus);
    		//处理一行SKU
    		foreach ($sku_arr as $key=>$val) {
    			if (trim($val) == '') {
    				unset($sku_arr[$key]);
    			}
    		}
    		foreach ($sku_arr as $key=>$sku) {
    			$self = $sku;
    			$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $self);
    			$_product = Mage::getModel('catalog/product')->load($_product->getId());
    			$rel_data = array();
    			foreach ($sku_arr as $key_rel=>$rel_sku) {
    				if ($key_rel != $key) {
    					$rel_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $rel_sku);
    					$rel_data[$rel_product->getId()] = array('position'=>$key_rel);
    				}
    			}
    			$_product->setRelatedLinkData($rel_data);
    			$_product->save();
    			var_dump('Product : ' . $_product->getSku());
    			var_dump($rel_data);
    		}
    	}
    }
    
    

}
	 

 

你可能感兴趣的:(table)