2011-06-15 53 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