English 中文(简体)
Magento - 我如何在现有产品中按方案添加标签?
原标题:Magento - How do I programmatically add tags to an existing product?
  • 时间:2012-05-24 08:54:07
  •  标签:
  • magento
  • tags

正如标题所言:“强”如何在程序上为现有产品添加一个或多个标签?“/强”我无法在互联网上找到任何关于这个话题的有用信息,因此欢迎一切帮助、链接或知识。

提前感谢!

最佳回答

Ok 是我自己找到的。 我复制并定制了 < strong > app/code/ code/ count/ Maage/ Tag/ currents/ Index current.php 的保存动作( ), 以及一些其他功能, 使此功能生效 。

require_once $_SERVER[ DOCUMENT_ROOT ] . "/app/Mage.php";
    umask(0);
    Mage::app();
    Mage::app()->getTranslator()->init( frontend );
    Mage::getSingleton( core/session , array( name  =>  frontend ));


$customerSession = Mage::getSingleton( customer/session );

$tagName    =  Urban Extraloud ;//(string) $this->getRequest()->getQuery( productTagName );
$productId  = 257;//(int)$this->getRequest()->getParam( product );

if(strlen($tagName) && $productId) {
    $session = Mage::getSingleton( catalog/session );
    $product = Mage::getModel( catalog/product )
        ->load($productId);
    if(!$product->getId()){
        //$session->addError($this->__( Unable to save tag(s). ));
    } else {
        try {
            $customerId = 58; //$customerSession->getCustomerId();
            $storeId = Mage::app()->getStore()->getId();

            $tagNamesArr = _cleanTags(_extractTags($tagName));

            $counter = new Varien_Object(array(
                "new" => 0,
                "exist" => array(),
                "success" => array(),
                "recurrence" => array())
            );

            $tagModel = Mage::getModel( tag/tag );
            $tagRelationModel = Mage::getModel( tag/tag_relation );

            foreach ($tagNamesArr as $tagName) {
                $tagModel->unsetData()
                    ->loadByName($tagName)
                    ->setStoreId($storeId)
                    ->setName($tagName);

                $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->setFirstCustomerId($customerId)
                        ->setFirstStoreId($storeId)
                        ->setStatus($tagModel->getPendingStatus())
                        ->save();

                    $tagRelationModel->setTagId($tagModel->getId())->save();
                    $counter->setNew($counter->getNew() + 1);
                } else {
                    $tagStatus = $tagModel->getStatus();
                    $tagRelationModel->setTagId($tagModel->getId());

                    switch($tagStatus) {
                        case $tagModel->getApprovedStatus():
                            if(_checkLinkBetweenTagProduct($tagRelationModel)) {
                                $relation = _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 = _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(_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) {

            print  Unable to save tag(s) ;
        }
    }
}






function _extractTags($tagNamesInString)
{
    return explode("
", preg_replace("/( (.*?) )|(s+)/i", "$1
", $tagNamesInString));
}

/**
 * Clears the tag from the separating characters.
 *
 * @param array $tagNamesArr
 * @return array
 */
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;
}


 /**
 * Checks whether the already marked this product in this store by this tag.
 *
 * @param Mage_Tag_Model_Tag_Relation $tagRelationModel
 * @return boolean
 */
function _checkLinkBetweenTagProduct($tagRelationModel)
{
    $customerId = $tagRelationModel->getCustomerId();
    $tagRelationModel->setCustomerId(null);
    $res = in_array($tagRelationModel->getProductId(), $tagRelationModel->getProductIds());
    $tagRelationModel->setCustomerId($customerId);
    return $res;
}


/**
 * Checks whether the already marked this product in this store by this tag and by this customer.
 *
 * @param Mage_Tag_Model_Tag_Relation $tagRelationModel
 * @param Mage_Tag_Model_Tag $tagModel
 * @return boolean
 */
function _checkLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)
{
    return (count(_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)
        ->getProductIds()) > 0);
}

/**
 * Get relation model for marked product in this store by this tag and by this customer.
 *
 * @param Mage_Tag_Model_Tag_Relation $tagRelationModel
 * @param Mage_Tag_Model_Tag $tagModel
 * @return Mage_Tag_Model_Tag_Relation
 */
function _getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)
{
    return Mage::getModel( tag/tag_relation )->loadByTagCustomer(
        $tagRelationModel->getProductId(),
        $tagModel->getId(),
        $tagRelationModel->getCustomerId(),
        $tagRelationModel->getStoreId()
    );
}
问题回答

这有点不同。 您不能将 < em>tags 添加到一个 产品 < / em > 上, 但必须在 产品 ids 上添加到 < em> tag 关系 上 。

$aProductIds = array(
    $my_product_id_1,
    $my_product_id_2
    // :
);

$oTag = Mage::getModel( tag/tag )
    ->load( my_tag_name ,  name );

Mage::getModel( tag/tag_relation )
    ->addRelations($oTag, $aProductIds);




相关问题
Automatically pick tags from context using Python

How can I pick tags from an article or a user s post using Python? Is the following method ok? Build a list of word frequency from the text and sort them. Remove some common words and pick the top ...

Embed font into PDF file by using iText

I defined a tag map, and got a XML data file. I want to convert the XML data file to PDF by using iText. The question is how to embed fonts (e.g. Polish font, Chinese font) into the target PDF when ...

Splitting a string in C#

I was wondering if somebody could help me use string split to get all occurrences of text in between <p> </p> tags in an HTML document?

Tagging Posts via Wordpress XMLRPC

i am trying to publish a new post to a wordpress blog over the XMLRPC API. This works out fine so far, but now i want to add tags to the post. Either at creation time or afterwards. But i can t find ...

linq query for tag system - search for multiple tags

I have two tables, Tags(tagid, postid, tagname) and posts(postid, name, ...) now i want to make a query that returns me all posts that have a generic amount of tags. like: i want all posts that have ...

Is it sometimes bad to use <BR />?

Is it sometimes bad to use <BR/> tags? I ask because some of the first advice my development team gave me was this: Don t use <BR/> ; instead, use styles. But why? Are there negative ...

iphone - Get dynamically created UITextField by tag

I add a UITextField to a table cell dynamically in my app. I d like to implement a "backgroundClick" method to dismiss the keyboard if the user presses outside the textfield (and outside the keyboard) ...

Re-insertion of <script> tags

Insertion of a file s tag, thus executing the file s code. Removal of the file s tag. Insertion of the same file s tag. Firebug does not seem to acknowledge and does not show the reinserted tag ...