我想过滤产品集合并对其进行分页。一切都很好,除了分页。我只是拿回了整个收藏,而不是第一页的3个项目。
//fetch all visible products
$product_collection = Mage::getModel('catalog/product')->getCollection();
//set wanted fields (nescessary for filter)
$product_collection->addAttributeToSelect('name');
$product_collection->addAttributeToSelect('description');
$product_collection->addAttributeToSelect('price');
$product_collection->addAttributeToFilter('visibility', array('neq' => 1));
//filter by name or description
$product_collection->addFieldToFilter(array(
array('attribute'=>'name','like'=>$sTerm),
array('attribute'=>'description','like'=>$sTerm)
));
//filter for max price
foreach ($product_collection as $key => $item) {
if($item->getPrice() >= $priceTo){
$product_collection->removeItemByKey($key);
}
}
//pagination (THIS DOESNT WORK!)
$product_collection->setPageSize(3)->setCurPage(1);
//TEST OUTPUT
foreach ($product_collection as $product) {
echo $product->getName().'<br />';
}
感谢您的支持!
你离得太近了!尝试在集合上的第一次foreach()
迭代之前移动$product_collection->setPageSize(3)->setCurPage(1);
行。
Magento收藏是懒惰加载的。在直接load()
它们(或通过调用count()
或foreach()
隐式加载它们)之前,您可以修改影响基础查询的集合属性(EDIT:请参阅下面的注释)。一旦显式或隐式加载集合,您将只获得已设置的_items
属性的成员。
仅供参考,您可以调用clear()
来保留影响原始查询的属性(筛选器、排序器、限制、联接等),然后添加更多的属性。
HTH-
EDIT:实际上,无论_items加载状态如何,都可以调整查询属性,但在重新生成集合之前,效果是不可见的。
谢谢@Ben!你给了我正确的提示。现在它确实起作用了!基本上,我正在创建另一个集合,并根据已经过滤的项目的ID来过滤这个集合。之后,很容易将分页添加到新集合中。这是工作代码:
//fetch all visible products
$product_collection = Mage::getModel('catalog/product')->getCollection();
//set wanted fields (nescessary for filter)
$product_collection->addAttributeToSelect('name');
$product_collection->addAttributeToSelect('description');
$product_collection->addAttributeToSelect('price');
$product_collection->addAttributeToFilter('visibility', array('neq' => 1));
//filter by name or description
$product_collection->addFieldToFilter(array(
array('attribute'=>'name','like'=>$sTerm),
array('attribute'=>'description','like'=>$sTerm)
));
//filter for max price
foreach ($product_collection as $key => $item) {
if($item->getPrice() >= $priceTo){
$product_collection->removeItemByKey($key);
}
}
//build id array out of filtered items (NEW!)
foreach($product_collection as $item){
$arrProductIds[]=$item->getId();
}
//recreate collection out of product ids (NEW)
$product_filtered_collection = Mage::getModel('catalog/product')->getCollection();
$product_filtered_collection->addAttributeToFilter('entity_id', array('in'=>$arrProductIds));
//add pagination (on new collection) (NEW)
$product_filtered_collection->setPageSize(3)->setCurPage(1);
//TEST OUTPUT
foreach ($product_filtered_collection as $product) {
echo $product->getName().'<br />';
}