代码之家  ›  专栏  ›  技术社区  ›  Tom

按类别划分的Magento产品

  •  14
  • Tom  · 技术社区  · 16 年前

    是否有人知道如何从视图文件中获取属于特定类别的产品列表? Magento ?

    8 回复  |  直到 7 年前
        1
  •  21
  •   Kerrek SB    13 年前

    可以使用MaMeNTO对象进行筛选。

    例子:

    $categoryId = 123; // a category id that you can get from admin
    $category = Mage::getModel('catalog/category')->load($categoryId);
    
    $products = Mage::getModel('catalog/product')
        ->getCollection()
        ->addCategoryFilter($category)
        ->load();
    
    print_r($products);
    
        2
  •  8
  •   Till    16 年前

    这完全取决于你所处的视野。;-)

    首先,我希望您保持在模板集中(在我的示例中是默认的)。

    把这个当作 例子 :

    <?php
    $_cat         = $this->getCurrentCategory();
    $_parent      = $_cat->getParentCategory();
    $_categories  = $_parent->getChildren();
    
    /* @var $category Mage_Catalog_Model_Category */
    $collection = Mage::getModel('catalog/category')->getCollection();
    /* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
    $collection->addAttributeToSelect('url_key')
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('is_anchor')
        ->addAttributeToFilter('is_active', 1)
        ->addIdFilter($_categories)
        ->setOrder('position', 'ASC')
        ->joinUrlRewrite()
        ->load();
    
    $productCollection = Mage::getResourceModel('catalog/product_collection');
    $layer             = Mage::getSingleton('catalog/layer');
    $layer->prepareProductCollection($productCollection);
    $productCollection->addCountToCategories($collection);
    // $productCollection should be ready here ;-)
    ?>
    

    我正在使用上面的代码在我的模板中显示姐妹类别-这并不理想,但它可以工作。

    这有点像黑客,因为我还没来得及学习所有布局XML的疯狂。否则,如果您使用的是xmls,您需要记住这一切都取决于您所处的位置。 在哪里? 是指模板文件和布局(根据app/design/frontend/default/default/layout/*)。

    我知道不多,但我希望能帮你开始。

        3
  •  7
  •   Mukesh Chapagain    10 年前

    下面是从任何特定类别获取产品的代码。你也可以在视图文件中使用这个文件。

    // if you want to display products from current category
    $category = Mage::registry('current_category'); 
    
    // if you want to display products from any specific category
    $categoryId = 10;
    $category = Mage::getModel('catalog/category')->load($categoryId);
    
    $productCollection = Mage::getResourceModel('catalog/product_collection')
                                     ->addCategoryFilter($category);
    
    // printing products name
    foreach ($productCollection as $product) {
        echo $product->getName(); 
        echo "<br />";
    }
    
        4
  •  5
  •   Jatin Soni    12 年前
    <?php
    $c_id = 2;
    $category = new Mage_Catalog_Model_Category();
    $category->load($c_id);
    $collection = $category->getProductCollection();
    $collection->addAttributeToSelect('*');
    foreach ($collection as $_product) { ?>
    <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?></a>
    <?php } ?>
    
        5
  •  3
  •   Raheel Hasan    13 年前

    我非常需要同样的东西。我是这样做的:

    $prod_whole = array();
    if(!empty($_menu)) //$_menu = array of Categories with some basic info
    foreach($_menu as $v)
    {
        if($v['name']=='HOME')
        continue;
    
        $cat_id = $v['id'];
    
        #/ Setup Products
        $category = Mage::getModel('catalog/category')->load($cat_id);
    
        $collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('*') // select all attributes
        ->addCategoryFilter($category)
        ->setPageSize(8) // limit number of results returned
        ->setCurPage(0)
        ->load()
        ;
    
    
        $prod_collection = array();
        foreach ($collection as $product)
        {
          $prod_collection_1 = array();
    
          #/ Basic Info
          $prod_collection_1['id'] = $product->getId();
          $prod_collection_1['name'] = $product->getName();
          $prod_collection_1['price'] = (float) $product->getPrice();
          //$prod_collection_1['desc'] = $product->getDescription();
          //$prod_collection_1['short'] = $product->getShortDescription();
          $prod_collection_1['type'] = $product->getTypeId();
          $prod_collection_1['status'] = $product->getStatus();
          $prod_collection_1['special_price'] =  $product->getSpecialPrice();
          $prod_collection_1['direct_url'] =  $product->getProductUrl();
    
    
          #/ getCategoryIds(); returns an array of category IDs associated with the product
          foreach ($product->getCategoryIds() as $category_id)
          {
              $category = Mage::getModel('catalog/category')->load($category_id);
              $prod_collection_1['parent_category'] = $category->getParentCategory()->getName();
              $prod_collection_1['category'] = $category->getName();
              //$prod_collection_1['category_idx'] = preg_replace('/[\s\'\"]/i', '_', strtolower(trim($prod_collection_1['category'])));
              $prod_collection_1['category_id'] = $category->getId();
          }
    
          #/gets the image url of the product
          $prod_collection_1['img'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
    
    
          $prod_collection[] = $prod_collection_1;
    
        }//end foreach.....
    
        $prod_whole[$cat_id] = $prod_collection;
    
    }//end foreach categories.......
    //var_dump('<pre>', $prod_whole);
    

    希望这有帮助。

        6
  •  3
  •   Mufaddal    12 年前
    <?php
    
        $category_id = 10; // if you know static category then enter number
    
    $catagory_model = Mage::getModel('catalog/category')->load($category_id); //where $category_id is the id of the category
    
    
    
         $collection = Mage::getResourceModel('catalog/product_collection');
    
            $collection->addCategoryFilter($catagory_model); //category filter
    
            $collection->addAttributeToFilter('status',1); //only enabled product
    
            $collection->addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched
    
            //$collection->getSelect()->order('rand()'); //uncomment to get products in random order    
    
            $collection->addStoreFilter();          
    
            if(!empty($collection))
    
            {
    
                    foreach ($collection as $_product):
    
                    echo $_product->getName();   //get product name        
    
                endforeach;
    
            }else
    
                {
    
                    echo 'No products exists';
    
            }              
    
        ?>
    
        7
  •  0
  •   Andrew    13 年前

    你应该避免把这样的代码放到视图中,这是非常糟糕的做法。 当视图可以被缓存时,也会遇到问题,导致意外的行为。

    您应该重写正在使用的块,并在其中放置代码。然后可以调用视图文件中的任何新方法。

    例如,可以复制mage_catalog_block_product_list

    发件人:app/code/core/catalog/block/product/list.php

    收件人:app/code/local/catalog/block/product/list.php

    然后,您可以添加一个新方法,可能使用上述文章中提到的一些代码。 新方法将在视图文件中可用(list.phtml或使用此块的任何视图)

        8
  •  0
  •   Shorabh    7 年前

    下面是一个代码,用于将所有类别的产品导出到csv中

    <?php 
    set_time_limit(0);
    ini_set("memory_limit",-1);
    ini_set('max_execution_time','1800000000');
    
    require_once '../app/Mage.php';
    Mage::app(); 
    
    $category = Mage::getModel('catalog/category');
    $tree = $category->getTreeModel();
    $tree->load();
    
    $ids = $tree->getCollection()->getAllIds();
    $fp = fopen('category-product-export.csv', 'w');
    $field = array('Product SKU','Category Name'); 
    fputcsv($fp, $field);
    
    $_productCollection = Mage::getModel('catalog/product')
                            ->getCollection()
                            ->addAttributeToSelect('*')
                            ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
                            ->load();
    
    foreach ($_productCollection as $_product){
       $cats = $_product->getCategoryIds();
       $cnt = 0;
       $catName = '';
        foreach($cats as $id) {
            $category->load($id);
            $root = 'Root Catalog';
                $isRoot = strtolower($root);
                $categoryName = strtolower($category->getName());
                if($categoryName == $isRoot){
                    continue;
                }
            $categories[$id]['name'] = $category->getName();
            $categories[$id]['path'] = $category->getPath();
    
            $path = explode('/', $categories[$id]['path']);
            $len = count($path);
            $string = '';
            if($id > 2){
                foreach ($path as $k=>$pathId)
                {
                    $separator = '';
                    if($pathId > 2){
                        $category->load($pathId);
                        if($k != $len-1){ $separator = ' || ';}
                        $string.= $category->getName() . $separator;
                    }
    
                }
                if($cnt > 0) {
                    $catName.= ','.$string;
                } else {
                    $catName = $string;
                }
    
                $cnt++;
            }
        }
        //echo $catName;
        $field = array($_product->getSku(),$catName); 
        fputcsv($fp, $field);   
    
    } 
    
    ?>
    <a href="category-product-export.csv">Download</a>