1

我目前正在为 Magento 编写自定义导入脚本,现在我想将产品从 CSV 文件添加到标签中。我在 StackOverflow 上使用了另一个问题的片段,但由于某种原因,它没有达到预期的效果。

function addTag($bundleProductId, $tagArray) {
    $tags = explode(',', $tagArray);
    array_walk($tags, 'trim_value');

    $customerId = NULL;
    $storeId = Mage::app()->getStore()->getId();
    $productId = $bundleProductId;

    $tagModel = Mage::getModel('tag/tag');
    //$tagModel->loadByName($tagName); // if not using a loop
    foreach ($tags as $tagName) {
    $tagModel->unsetData()->loadByName($tagName); //if using a loop 

        if (!$tagModel->getId()) {
             $tagModel->setName($tagName)
                  ->setFirstCustomerId($customerId)
                  ->setFirstStoreId($storeId)
                  ->setStatus($tagModel->getPendingStatus())
                  ->save();
        }
   $relationStatus = $tagModel->saveRelation($productId, $customerId, $storeId);
    }
}

脚本运行后,管理面板在“产品”列中显示带有“1”的新标签(如预期的那样),但是当我编辑标签时,没有选择任何内容。

4

1 回答 1

1

在查看完整代码之前很难找到。但无论如何,我在这里包含了另一段我经常使用它并且工作正常的代码。

<?php

class Mage_Catalog_Model_Convert_Adapter_ProductTags extends Mage_Catalog_Model_Convert_Adapter_Product {


public function saveRow(array $importData) {
    $product = $this->getProductModel ();
    $product->setData ( array () );
    if ($stockItem = $product->getStockItem ()) {
        $stockItem->setData ( array () );
    }
    $product = Mage::getModel('catalog/product');
    $productId='';
    $productId = $product->getIdBySku($importData['sku']);  
    $tagNames = $importData['product_tags'];
    if (empty ( $importData ['sku'] )) {
        $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not defined', 'sku' );
        Mage::throwException ( $message );
    }       
    if ( !$productId ) {
        $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not Valid Sku', $importData['sku'] );
        Mage::throwException ( $message );
    }
    if(strlen($tagNames) && $productId) {
        $session = Mage::getSingleton('catalog/session');
        $product = Mage::getModel('catalog/product')
            ->load($productId);
            $productId =$product->getId();
        if(!$product->getId()){
           $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not valid', 'sku' );
            Mage::throwException ( $message );
        } else {
            try {
              $customerId = NULL;
              $storeId = 1;
              $tagModel='';                 
              $counter = new Varien_Object(array(
                        "new" => 0,
                        "exist" => array(),
                        "success" => array(),
                        "recurrence" => array())
                        );                  
               $tagModel = Mage::getModel('tag/tag');
               $tagRelationModel = Mage::getModel('tag/tag_relation');
               $tagNamesArr = $this->_cleanTags($this->_extractTags($tagNames));
               foreach ($tagNamesArr as $tagName) {
                    $tagModel->unsetData()
                            ->loadByName($tagName)
                            ->setName($tagName)
                            ->setFirstCustomerId($customerId)
                            ->setFirstStoreId($storeId)
                            ->setStatus(1)
                            ->save();

                    $tagRelationModel->unsetData()
                        ->setStoreId($storeId)
                        ->setProductId($productId)
                        ->setCustomerId($customerId)
                        ->setActive(Mage_Tag_Model_Tag_Relation::STATUS_ACTIVE)
                        ->setCreatedAt( $tagRelationModel->getResource()->formatDate(time()) );

                    if (!$tagModel->getId()) {  
                        $tagModel->setName($tagName)
                            ->setFirstCustomerId($customerId)
                            ->setFirstStoreId($storeId)
                            ->setStatus($tagModel->getPendingStatus())
                            ->save();
                        $relationStatus = $tagModel->saveRelation($productId, $customerId, $storeId);
                        $counter[$relationStatus][] = $tagName; 
                        $tagRelationModel->setTagId($tagModel->getId())->save();
                        $counter->setNew($counter->getNew() + 1);
                    }
                    else { 
                        $tagStatus = $tagModel->getStatus();
                        $tagRelationModel->setTagId($tagModel->getId());
                        $relationStatus = $tagModel->saveRelation($productId, $customerId,'');
                        $counter[$relationStatus][] = $tagName; 
                        switch($tagStatus) {
                            case $tagModel->getApprovedStatus(): 
                                if($this->_checkLinkBetweenTagProduct($tagRelationModel)) { 
                                    $relation = $this->_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel);
                                    if ($relation->getId()) {
                                        if (!$relation->getActive()) {
                                            $tagRelationModel
                                                ->setId($relation->getId())
                                                ->save();
                                        }
                                    } 
                                    else { 
                                        $tagRelationModel->save();
                                    }                                       
                                    $counter->setExist(array_merge($counter->getExist(), array($tagName)));
                                } 
                                else { 
                                    $tagRelationModel->save(); 
                                    $counter->setSuccess(array_merge($counter->getSuccess(), array($tagName)));
                                }
                                break;
                            case $tagModel->getPendingStatus(): 
                                $relation = $this->_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel);
                                if ($relation->getId()) {
                                    if (!$relation->getActive()) {
                                        $tagRelationModel
                                            ->setId($relation->getId())
                                            ->save();
                                    }
                                } 
                                else {
                                    $tagRelationModel->save();
                                }
                                $counter->setNew($counter->getNew() + 1);
                                break;
                            case $tagModel->getDisabledStatus():
                                if($this->_checkLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)) {
                                    $counter->setRecurrence(array_merge($counter->getRecurrence(), array($tagName)));
                                } 
                                else {
                                    $tagModel->setStatus($tagModel->getPendingStatus())->save();
                                    $tagRelationModel->save();
                                    $counter->setNew($counter->getNew() + 1);
                                }
                            break;
                        }
                    }
                }
            } catch (Exception $e) {
                Mage::logException($e);
                $message='Unable to save tag(s).';
                Mage :: throwException( $e.$message );
            }
        }
    }               
    return true;
}

   protected function _getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel){
        return Mage::getModel('tag/tag_relation')->loadByTagCustomer(
            $tagRelationModel->getProductId(),
            $tagModel->getId(),
            $tagRelationModel->getCustomerId(),
            $tagRelationModel->getStoreId()
          );
    }

     protected function _checkLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel){
        return (count($this->_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)
            ->getProductIds()) > 0);
    }   
    protected function _checkLinkBetweenTagProduct($tagRelationModel){      
        $customerId = $tagRelationModel->getCustomerId();
        $tagRelationModel->setCustomerId(null);
        $res = in_array($tagRelationModel->getProductId(), $tagRelationModel->getProductIds());
        $tagRelationModel->setCustomerId($customerId); 
        return $res;
    }
    protected function _cleanTags(array $tagNamesArr){
        foreach( $tagNamesArr as $key => $tagName ){
            $tagNamesArr[$key] = trim($tagNamesArr[$key], '\'');
            $tagNamesArr[$key] = trim($tagNamesArr[$key]);
            if( $tagNamesArr[$key] == '' ) {
                unset($tagNamesArr[$key]);
            }
        }
        return $tagNamesArr;
    }
    protected function _extractTags($tagNamesInString){
        return explode("\n", preg_replace("/(\'(.*?)\')|(\s+)/i", "$1\n", $tagNamesInString));
    }   
    protected function userCSVDataAsArray($data) {
        return explode ( ',', str_replace ( " ", "", $data ) );
    }
    protected function skusToIds($userData, $product) {
        $productIds = array ();
        foreach ( $this->userCSVDataAsArray ( $userData ) as $oneSku ) {
            if (($a_sku = ( int ) $product->getIdBySku ( $oneSku )) > 0) {
                parse_str ( "position=", $productIds [$a_sku] );
            }
        }
        return $productIds;
    }

//// Para importar categorias
    protected $_categoryCache = array ();
    protected function _addCategories($categories, $store) {
        $rootId = $store->getRootCategoryId ();
        if (! $rootId) {
            return array ();
        }
        $rootPath = '1/' . $rootId;
        if (empty ( $this->_categoryCache [$store->getId ()] )) {
            $collection = Mage::getModel ( 'catalog/category' )->getCollection ()->setStore ( $store )->addAttributeToSelect ( 'name' );
            $collection->getSelect ()->where ( "path like '" . $rootPath . "/%'" );
            foreach ( $collection as $cat ) {
                $pathArr = explode ( '/', $cat->getPath () );
                $namePath = '';
                for($i = 2, $l = sizeof ( $pathArr ); $i < $l; $i ++) {
                    $name = $collection->getItemById ( $pathArr [$i] )->getName ();
                    $namePath .= (empty ( $namePath ) ? '' : '/') . trim ( $name );
                }
                $cat->setNamePath ( $namePath );
            }               
            $cache = array ();
            foreach ( $collection as $cat ) {
                $cache [strtolower ( $cat->getNamePath () )] = $cat;
                $cat->unsNamePath ();
            }
            $this->_categoryCache [$store->getId ()] = $cache;
        }
        $cache = & $this->_categoryCache [$store->getId ()];            
        $catIds = array ();
        foreach ( explode ( ',', $categories ) as $categoryPathStr ) {
            $categoryPathStr = preg_replace ( '#s*/s*#', '/', trim ( $categoryPathStr ) );
            if (! empty ( $cache [$categoryPathStr] )) {
                $catIds [] = $cache [$categoryPathStr]->getId ();
                continue;
            }
            $path = $rootPath;
            $namePath = '';
            foreach ( explode ( '/', $categoryPathStr ) as $catName ) {
                $namePath .= (empty ( $namePath ) ? '' : '/') . strtolower ( $catName );
                if (empty ( $cache [$namePath] )) {
                    $cat = Mage::getModel ( 'catalog/category' )->setStoreId ( $store->getId () )->setPath ( $path )->setName ( $catName )->// comment out the following line if new categories should stay inactive
                    setIsActive ( 1 )->save ();
                    $cache [$namePath] = $cat;
                }
                $catId = $cache [$namePath]->getId ();
                $path .= '/' . $catId;
            }
            if ($catId) {
                $catIds [] = $catId;
            }
        }
        return join ( ',', $catIds );
    }
}   

`

我几个月前从某个地方下载了它。配置本地模块(实际上覆盖核心系统)将此文件放置在此位置.app\code\local\Mage\Catalog\Model\Convert\Adapter\ 然后,转到管理部分并转到系统->导入/导出/高级配置文件单击创建新配置文件将配置文件名称作为产品标签导入并在操作 XML * 粘贴下面的代码

<action type="dataflow/convert_adapter_io" method="load"> 
                <var name="type">file</var> 
                <var name="path">var/import</var> 
                <var name="filename"><![CDATA[tag_file.csv]]></var> 
                <var name="format"><![CDATA[csv]]></var> 
            </action> 

            <action type="dataflow/convert_parser_csv" method="parse"> 
                <var name="delimiter"><![CDATA[,]]></var> 
                <var name="enclose"><![CDATA["]]></var> 
                <var name="fieldnames">true</var> 
                <var name="store"><![CDATA[0]]></var> 
                <var name="number_of_records">1</var> 
                <var name="decimal_separator"><![CDATA[.]]></var> 
                <var name="adapter">catalog/convert_adapter_ProductTags</var> 
                <var name="method">parse</var> 
            </action>

tag_file.csv 是您的导入数据文件。该文件仅包含 2 个字段,sku 和 product_tags。添加您的产品 sku 和相应的标签。并将该文件放在您的 var/import 目录中。如上所述,您可以在管理部分查看此文件。而已 ..!!让我知道是否有任何问题。

于 2013-10-02T10:50:02.860 回答