製品コレクションのカスタムソート
-
16-10-2019 - |
質問
次のシナリオを実装する必要があります。
カテゴリ(位置)のデフォルトのソート順序では、カテゴリ内の製品の位置セットを無視する必要があります。
代わりに、位置でソートするときは、このルールに従う必要があります。
- 上部の最後のX日に追加された製品(Xは構成可能です)。
- 下部に割引(特別価格またはカタログルール)がある製品。
- 上記の2つのケースの間の残りの製品。
私のアプローチは書き直すことです Mage_Catalog_Model_Resource_Product_Collection::addAttributeToSort()
. 。属性コードが渡された場合 position
カスタムコードを実行する必要があります。さもないと parent::addAttributeToSort()
.
しかし、私のカスタムコードはどうあるべきでしょうか?
すべての製品はシンプルまたは構成可能です。
この場合、私のルールに基づいて時々ポジションを更新するクロンを実行することは有効なオプションではありません。
解決
Ok。質問を投稿する前に、さらに1時間待つ必要があります。
これは機能します。
書き直しました Mage_Catalog_Model_Resource_Product_Collection::addAttributeToSort()
そして、それを次のようにしました(きれいなコードではありませんが、動作し、階層化されたナビゲーションなど):
<?php
class Namespace_Catalog_Model_Resource_Product_Collection
extends Mage_Catalog_Model_Resource_Product_Collection {
public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC){
//don't screw up the admin sorting.
if (Mage::app()->getStore()->getId() == Mage_Core_Model_App::ADMIN_STORE_ID){
return parent::addAttributeToSort($attribute, $dir);
}
if ($attribute == 'position') { //if should sort by position
$newLimit = SOME code to get the limit date for products added after X days;
$this->addExpressionAttributeToSelect(
'sort_position',
"(CASE WHEN {{created_at}} >= '{$newLimit}' THEN 0 ELSE 1 END)",
array('created_at'=>'created_at')
); //select a 0|1 flag field. If the product is new then it has the value 0 else it's 1
$this->addExpressionAttributeToSelect(
'discount',
'(CASE WHEN (price_index.price - price_index.min_price) > 0 THEN 1 ELSE 0 END)',
array()
);// select a 0|1 flag field. If the product has a discount then 1 else 0
$this->getSelect()->order(array('sort_position '.$dir, 'discount '.$dir)); //sort by my new fields keeping the direction selected by the user
return $this;
}
else { //if should sort by something else let Magento do it's magic.
return parent::addAttributeToSort($attribute, $dir);
}
}
}
所属していません magento.stackexchange