2011-06-15 23 views
4

我之前發佈了一個關於此問題的問題,但現在我有更多的信息,我認爲最好發佈一個新的而不是修改(對不起,如果這不是合適的協議)。你可以找到我的原始問題here獲取第一個收藏品而不會破壞尋呼機

無論如何,最初的問題是我想在設置集合後檢查List.php類中集合中的第一個項目,以便我可以刮取類別並使用它來顯示評論。這是基於一個自定義模塊,所以有很多變量。我已經在默認的Magento樣本商店嘗試了它,並且只添加ONE行到app/code/core/Mage/catalog/Block/Product/List.php以打破尋呼機。這裏是細節。如果您有任何想法,爲什麼發生這種情況,請讓我知道,因爲我卡住了

首先,打開app/code/core/Mage/catalog/Block/Product/List.php並找到_getProductCollection函數。在if (is_null...)塊的末尾添加$_foo123 = $this->_productCollection->getFirstItem();讓您擁有一個功能,看起來像這樣:

protected function _getProductCollection() 
{ 
    if (is_null($this->_productCollection)) { 
     $layer = $this->getLayer(); 
     /* @var $layer Mage_Catalog_Model_Layer */ 
     if ($this->getShowRootCategory()) { 
      $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId()); 
     } 

     // if this is a product view page 
     if (Mage::registry('product')) { 
      // get collection of categories this product is associated with 
      $categories = Mage::registry('product')->getCategoryCollection() 
      ->setPage(1, 1) 
      ->load(); 
      // if the product is associated with any category 
      if ($categories->count()) { 
       // show products from this category 
       $this->setCategoryId(current($categories->getIterator())); 
      } 
     } 

     $origCategory = null; 
     if ($this->getCategoryId()) { 
      $category = Mage::getModel('catalog/category')->load($this->getCategoryId()); 
      if ($category->getId()) { 
       $origCategory = $layer->getCurrentCategory(); 
       $layer->setCurrentCategory($category); 
      } 
     } 
     $this->_productCollection = $layer->getProductCollection(); 

     $this->prepareSortableFieldsByCategory($layer->getCurrentCategory()); 

     if ($origCategory) { 
      $layer->setCurrentCategory($origCategory); 
     } 

     //THIS LINE BREAKS THE PAGER 
     $_foo123 = $this->_productCollection->getFirstItem(); 
    } 

    return $this->_productCollection; 
} 

現在,簡單地去使用這個類(分類視圖,例如)任何產品列表,你會明白了嗎。無論你在下選擇什麼,在工具欄上顯示XX每頁,它總是會顯示列表中的所有項目。如果你註釋掉$_foo123...行,它可以正常工作。

什麼給?

P.S.我知道我不應該修改的核心文件......這僅僅是一個例子:)

回答

14

的原因是因爲當你在收集調用getFirstItem()(或幾乎任何其他檢索方法)收集加載。任何後續操作都會忽略數據庫並僅使用加載的數據,因爲它們只是SQL,所以過濾器不起作用,對於分頁和選定的列也是如此。解決方法是使用基於第一個集合的第二個集合。

$secondCollection = clone $firstCollection; 
$secondCollection->clear(); 
$_foo123 = $secondCollection->getFirstItem(); 

clear()方法卸載爲收集數據,迫使其下次再訪問數據庫。

+0

謝謝!我知道要求集合中的項目有效地加載它,但我沒有意識到這會影響分頁。我認爲整個系列都是收藏品,傳呼機向你展示了它的一部分,但我猜不是。男人,這東西可以混亂! 有一個問題......你的意思是把'clear()'line _before_ getFirstItem()'調用嗎?似乎反直覺... – BrianVPS 2011-06-15 19:48:36

+0

我第二集合之前有意使用'clear()'在第一集合已被加載的情況下。克隆克隆了一切。 – clockworkgeek 2011-06-15 20:20:16

+0

克隆收集完全加載 - 當它包含所有項目時不是更好嗎?然後你不必清除它 - 你只需克隆完整的集合,然後調用你調用的getFirstItem()' – 2017-02-15 08:42:05