[英]Magento product collection pagination with custom sort
我通過添加以下內容來覆蓋Mage_Catalog_Block_Product_List的_getProductCollection :
foreach ($this->_productCollection as $product) {
$product->setDistance(Mage::helper('myhelper')->getDistance($product));
}
現在,我希望按距離對集合進行排序,我嘗試了以下操作:
$this->_productCollection = Mage::helper('myhelper')->sortProductByDist($this->_productCollection);
排序的幫助程序如下(從SO竊取的):
public function sortProductByDist($products) {
$sortedCollection = Mage::getSingleton('catalog/layer')
->getProductCollection()->addFieldToFilter('entity_id', 0);
$sortedCollection = $sortedCollection->clear();
$collectionItems = $products->getItems();
usort($collectionItems, array($this,'_sortItems'));
foreach ($collectionItems as $item) {
$sortedCollection->addItem($item);
}
return $sortedCollection;
}
protected function _sortItems($a, $b) {
$order = 'asc';
$al = strtolower($a->getDistance());
$bl = strtolower($b->getDistance());
if ($al == $bl) {
return 0;
}
if ($order == 'asc') {
return ($al < $bl) ? -1 : 1;
} else {
return ($al > $bl) ? -1 : 1;
}
}
問題在於,應用此附加排序后,產品集合將不再被分頁。
有人知道如何解決這個問題嗎?
您沒有以正確的方式進行操作,並且沒有簡單的解決方案。 您需要使用數據庫進行排序。
_productCollection不是數組,它是一個具有引用的對象,此時查詢仍然可以更新,分頁將由查詢處理到數據庫。
如果你做一個
Mage::log((string) $this->_productCollection->getSelect());
您將在日志中看到查詢
您要做的是加載當前頁面的產品,在該頁面的所有產品上添加距離,並在其中添加項以創建一個新集合。因此,集合的數據不是來自數據庫,而僅包含元素當前頁面的
使用php排序不是一個好主意,因為如果您有很多產品,則意味着您需要從數據庫中全部加載它們。 那會很慢。
通過修改查詢直接在數據庫中計算距離。
您可以編輯選擇查詢並在數據庫中進行距離計算
$this->_productCollection
->getSelect()
->columns("main.distance as distance")
現在您可以在產品集合上添加排序
$this->_productCollection->setOrder('distance');
復雜的部分將是在mysql中編寫與getDistance方法等效的方法。 在我的示例中,我假設距離已經在數據庫中。
不要猶豫,在各個步驟中打印查詢以了解發生了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.