Magento - Невозможно установить порядок сбора


11

Это, кажется, не упорядочено правильно, что-то я делаю не так? Предложения?

$componentQuantityCollection = Mage::getModel('catalog/product')->getCollection();
$componentQuantityCollection->joinField('qty',
    'cataloginventory/stock_item',
    'qty',
    'product_id=entity_id',
    '{{table}}.stock_id=1',
    'left');
$componentQuantityCollection->addAttributeToFilter('sku', array('in' => $componentSkus))->setOrder('sku','ASC');

Другая коллекция, которая, кажется, не отсортирована, отличается от первой:

$kitCollection = Mage::getModel('kitinventory/kitinventory')->getCollection()->addFieldToFilter('kit_sku', $sku)->setOrder('related_sku', 'DESC');

Ответы:


42

Коллекции EAV работают с атрибутами, метод сортировки здесь тоже немного другой

$componentQuantityCollection->addAttributeToSort('sku', 'ASC');

Для коллекций без EAV используйте один из следующих методов

$kitCollection->getSelect()->order('related_sku DESC');
$kitCollection->setOrder('related_sku', 'DESC');

что насчет второй коллекции?
easymoden00b

Это коллекция плоского типа, поэтому нет EAV и атрибутов. Посмотрите на этот ответ о том, как это отсортировать: stackoverflow.com/a/11354060
Сандер Мангель

Я пробовал setOrder ('related_sku', 'DESC'); но это не отсортировано.
easymoden00b

Я отредактировал свой ответ
Сандер Мангель

2
@ easymoden00b используйте это$kitCollection->getSelect()->order('related_sku DESC');
Priyank

15

Вы можете добавить порядок сортировки следующим образом:

$kitCollection->getSelect()->order('related_sku DESC');

Дополнительная информация: http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/using_collections_in_magento

Надежда может помочь вам.


3
Исправил это для меня, потому что я использовал это как->order('related_sku', 'desc');
Рикки Один Мэттьюс

3

Чтобы расширить другие ответы здесь, $kitCollection->getSelect()->order('column DESC')работает нормально, но вы не можете добавить более одного столбца. Например, $kitCollection->getSelect()->order('column DESC, column2 ASC')будет ошибка. Это из-за работы, которую Magento делает, чтобы избежать имен столбцов. Чтобы обойти это, вы можете использовать Zend_Db_Exprтак:

$kitCollection->getSelect()->order(new Zend_Db_Expr('related_sku DESC, column2 ASC'));

1

easymoden00b, setOrder()не работает из-за структуры Eav для продукта. Как @Sande говорят использовать addAttributeToSort()функцию, из-за

  • Magento is join multiple tables for product collection.

  • Attribute alias name at collection

  • setOrder() functionработает, когда это order expression Fieldname, SortOrder есть correct.

Вы можете увидеть, как magento создает псевдоним поля и как он связан с атрибутом таблицы eav в классе Mage_Eav_Model_Entity_Collection_Abstract

public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC)
{
    if (isset($this->_joinFields[$attribute])) {
        $this->getSelect()->order($this->_getAttributeFieldName($attribute).' '.$dir);
        return $this;
    }
    if (isset($this->_staticFields[$attribute])) {
        $this->getSelect()->order("e.{$attribute} {$dir}");
        return $this;
    }
    if (isset($this->_joinAttributes[$attribute])) {
        $attrInstance = $this->_joinAttributes[$attribute]['attribute'];
        $entityField = $this->_getAttributeTableAlias($attribute) . '.' . $attrInstance->getAttributeCode();
    } else {
        $attrInstance = $this->getEntity()->getAttribute($attribute);
        $entityField = 'e.' . $attribute;
    }

    if ($attrInstance) {
        if ($attrInstance->getBackend()->isStatic()) {
            $orderExpr = $entityField;
        } else {
            $this->_addAttributeJoin($attribute, 'left');
            if (isset($this->_joinAttributes[$attribute])||isset($this->_joinFields[$attribute])) {
                $orderExpr = $attribute;
            } else {
                $orderExpr = $this->_getAttributeTableAlias($attribute).'.value';
            }
        }

        if (in_array($attrInstance->getFrontendClass(), $this->_castToIntMap)) {
            $orderExpr = Mage::getResourceHelper('eav')->getCastToIntExpression(
                $this->_prepareOrderExpression($orderExpr)
            );
        }

        $orderExpr .= ' ' . $dir;
        $this->getSelect()->order($orderExpr);
    }
    return $this;
}

1

Вот мое решение для сортировки порядка параметров в атрибуте настраиваемого продукта. Начните с копирования Collection.php,

app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.phpк app/code/local/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php.

Тогда вы можете найти этот код:

foreach ($this->getProduct()->getTypeInstance(true)->getUsedProducts(array($productAttribute->getAttributeCode()), $this->getProduct()) as $associatedProduct) {

И замените его следующим кодом:

$assProds = $this->getProduct()->getTypeInstance(true)->getUsedProducts(array($productAttribute->getAttributeCode()), $this->getProduct());
sort($assProds);
foreach ($assProds as $associatedProduct) {

Это позволит вам отсортировать выпадающий список параметров атрибута по алфавиту. Вы также можете изменить порядок с помощью array_reverse()или аналогичных функций.

Ранее параметры моего атрибута были в обратном алфавитном порядке. Теперь они в алфавитном порядке.

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.