您的位置:首页 > 其它

magento按分类批量添加up-sell产品

2012-10-30 12:12 591 查看
require_once 'app/Mage.php';
set_time_limit(0);
Mage::app('default');

//获取所有分类
function nodeToArray(Varien_Data_Tree_Node $node) {
$result = array();
$result['category_id'] = $node->getId();
$result['parent_id'] = $node->getParentId();
$result['name'] = $node->getName();
$result['is_active'] = $node->getIsActive();
$result['position'] = $node->getPosition();
$result['level'] = $node->getLevel();
$result['children'] = array();

foreach ($node->getChildren() as $child) {
$result['children'][] = nodeToArray($child);
}

return $result;
}

function load_tree() {
$store = 1;
$parentId = 2;

$tree = Mage::getResourceSingleton('catalog/category_tree')
->load();

$root = $tree->getNodeById($parentId);

if ($root && $root->getId() == 1) {
$root->setName(Mage::helper('catalog')->__('Root'));
}

$collection = Mage::getModel('catalog/category')->getCollection()
->setStoreId($store)
->addAttributeToSelect('name')
//->addAttributeToSelect('id')
->addAttributeToSelect('is_active');

$tree->addCollectionData($collection, true);

return nodeToArray($root);
}

function getCatList($tree) {
$cat_list = array();
foreach ($tree as $item) {
$cat = array();
$cat['id'] = $item['category_id'];
$cat['is_active'] = $item['is_active'];

$product = array();
$category = Mage::getModel('catalog/category')->load($item['category_id']);
$products = $category->getProductCollection();
foreach($products as $val)
{
$product[] = $val->getId();
}
$cat['products'] = $product;
$cat_list[$cat['id']] = $cat;
getCatList($item['children']);
}
return $cat_list;
}

$tree = load_tree();
$cat_list = getCatList($tree['children']);

//--------------------------------------获取所有分类-------------------------------------//
$itemsLimit = 8;
$collection = Mage::getResourceModel('catalog/product_collection')->load();
foreach($collection as $item)
{
$oldCount = count($item->getUpSellProducts());
if($oldCount < $itemsLimit)
{
//$itemsLimit = $itemsLimit - $oldCount;
$cat_arr = array();
$product_id = $item->getId();
$categories = $item->getCategoryCollection();
foreach($categories as $_category) {
if($cat_list[$_category['entity_id']]['is_active'] == 1)
{
$upsells = array_rand($cat_list[$_category['entity_id']]['products'], $itemsLimit+1);
$i = $oldCount;
$link = array();
foreach($upsells as $up)
{
$realtedid = $cat_list[$_category['entity_id']]['products'][$up];
if($realtedid != $product_id)
{
$link[$realtedid] = array('position' => null);
}
$i++;
if($i >= $itemsLimit){break;}
}
print_r($link);echo $product_id . "<br />";
$item->setUpSellLinkData($link);
Mage::dispatchEvent('catalog_product_prepare_save', array('product' => $item));
$item->save();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: