2012-03-22 99 views
0

BElow是選擇單一產品相關產品的功能。我希望它能夠以這樣的方式工作,如果沒有相關產品,其他隨機產品將被添加到陣列中。隨機可以是同一類別的其他產品,並且如果在同一類別中沒有切割,我們可以從其他類別獲取。隨機產品代替magento中的相關產品

protected function _prepareData() 
    { 
     $product = Mage::registry('product'); 
     /* @var $product Mage_Catalog_Model_Product */ 

     $this->_itemCollection = $product->getRelatedProductCollection() 
      ->addAttributeToSelect('required_options') 
      ->addAttributeToSort('position', Varien_Db_Select::SQL_ASC) 
      ->addStoreFilter() 
     ; 

     if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) { 
      Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection, 
       Mage::getSingleton('checkout/session')->getQuoteId() 
      ); 
      $this->_addProductAttributesAndPrices($this->_itemCollection); 
     } 
//  Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_itemCollection); 
     Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection); 

     $this->_itemCollection->load(); 

     foreach ($this->_itemCollection as $product) { 
      $product->setDoNotUseCategoryId(true); 
     } 

     return $this; 
    } 

感謝 Abnab

回答

1

您可以使用count(),看看是否有任何相關產品。如果沒有,那麼你可以用你想要的任何過濾器加載一個新的產品集合。作爲一個例子,我通過category_id在下面進行過濾。我建議您閱讀Magento collections(或here)。

protected function _prepareData() 
{ 
... 
    $this->_itemCollection->load(); 

    // If there are no related products, find more products in same category. 
    if (count($this->_itemCollection) < 1) { 
     $this->_itemCollection = Mage::getModel('catalog/product')->getCollection() 
      ->addAttributeToSelect('required_options') 
      ->addAttributeToFilter('category_id', $product->getCategoryId()); 
    } 

    foreach ($this->_itemCollection as $product) { 
...