How To: Сортировка и фильтрация по цене

Указание направления сортировки возможно напрямую контроллеру показа Shop_Controller_Show методом ->orderBy($column, $direction = 'ASC'), при сортировке по цене вы можете указывать price или absolute_price (синонимы), при этом расчет absolute_price будет добавлен автоматически.

Сортировка по цене, по возрастанию

$Shop_Controller_Show->orderBy('price', 'ASC');

Сортировка по цене, по убыванию

$Shop_Controller_Show->orderBy('price', 'DESC');

Фильтрация по цене, от

$Shop_Controller_Show->addFilter('price', '>', $price_from);

Фильтрация по цене, до

$Shop_Controller_Show->addFilter('price', '<=', $price_to);

Сортировка и фильтр (в устаревших версиях до 6.9.1)

Ограничения на вывод товаров задаются через метод shopItems() контроллера Shop_Controller_Show, метод возвращает объект Shop_Item_Model с настроенными ограничениями.

Фильтрацию и сортировку будем производить по вычисляемому в запросе полю absolute_price, которое вычисляется с учетом валюты товара и примененных к товару скидок.

// Получаем список валют магазина
$aShop_Currencies = Core_Entity::factory('Shop_Currency')->findAll();

$query_tax = 'IF(`shop_taxes`.`tax_is_included` IS NULL OR `shop_taxes`.`tax_is_included` = 1, 0, `shop_items`.`price` * `shop_taxes`.`rate` / 100)';
$query_currency_switch = "`shop_items`.`price` + {$query_tax}";
foreach ($aShop_Currencies as $oShop_Currency)
{
    // Получаем коэффициент пересчета для каждой валюты
    $currency_coefficient = Shop_Controller::instance()->getCurrencyCoefficientInShopCurrency(
        $oShop_Currency, $oShop->Shop_Currency
    );

   $query_currency_switch = "IF (`shop_items`.`shop_currency_id` = '{$oShop_Currency->id}', IF (COUNT(`shop_discounts`.`id`), ((`shop_items`.`price` + {$query_tax}) * (1 - SUM(DISTINCT IF(`shop_discounts`.`type` = 0, `shop_discounts`.`value`, 0)) / 100)) * {$currency_coefficient} - SUM(DISTINCT IF(`shop_discounts`.`type`, `shop_discounts`.`value`, 0)), (`shop_items`.`price`) * {$currency_coefficient}), {$query_currency_switch})";
}

$current_date = date('Y-m-d H:i:s');
$Shop_Controller_Show->shopItems()
    ->queryBuilder()
    ->select(array(Core_QueryBuilder::expression($query_currency_switch), 'absolute_price'))
    ->leftJoin('shop_item_discounts', 'shop_items.id', '=', 'shop_item_discounts.shop_item_id')
    ->leftJoin('shop_discounts', 'shop_item_discounts.shop_discount_id', '=', 'shop_discounts.id', array(
        array('AND ' => array('shop_discounts.active', '=', 1)),
        array('AND ' => array('shop_discounts.deleted', '=', 0)),
        array('AND' => array('shop_discounts.start_datetime', '<=', $current_date)),
        array('AND (' => array('shop_discounts.end_datetime', '>=', $current_date)),
        array('OR' => array('shop_discounts.end_datetime', '=', '0000-00-00 00:00:00')),
        array(')' => NULL)
    ))
    ->leftJoin('shop_taxes', 'shop_taxes.id', '=', 'shop_items.shop_tax_id')
    ->groupBy('shop_items.id');

Сортировка по цене, по возрастанию (в устаревших версиях до 6.9.1)

$Shop_Controller_Show->shopItems()->queryBuilder()
    ->clearOrderBy()
    ->orderBy('absolute_price', 'ASC');

Сортировка по цене, по убыванию (в устаревших версиях до 6.9.1)

$Shop_Controller_Show->shopItems()->queryBuilder()
    ->clearOrderBy()
    ->orderBy('absolute_price', 'DESC');

Фильтрация по цене, от (в устаревших версиях до 6.9.1)

$Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '>=', $price_from);
$Shop_Controller_Show->addCacheSignature('price_from=' . $price_from);

Фильтрация по цене, до (в устаревших версиях до 6.9.1)

$Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '<=', $price_to);
$Shop_Controller_Show->addCacheSignature('price_to=' . $price_to);

Не нашли ответ на свой вопрос в документации? Направьте обращение в службу поддержки или онлайн чат.