Magento – Category order does not work, always sort by the entity_id desc

categorycollection;magento2.2product

I have a problem with my categories, and I don´t know if this is normal or not.

In Magento 2.2.2 I created a custom attribute, and added it for sorting attributes. But when I tried to order product list with this attributes, they didn´t move. I create a observer to listen catalog_product_collection_load_after event, to get the collection query:

$productCollection = $observer->getEvent()->getCollection();
$select  = $productCollection->getSelect()->assemble();
echo $productCollection->getSelect()->__toString();

And I saw that in the ORDER BY part of the query, it is not only ordered by my custom attribute:

... ORDER BY `e`.`entity_id` DESC, `equipo_original` DESC LIMIT 9

equipo_original is my custom attribute, but the query is sorting first to entity_id (and always desc) and in second place with my attribute. I tried with name and position, and result was the same:

... ORDER BY `e`.`entity_id` DESC, `cat_index`.`position` DESC LIMIT 9

... ORDER BY `e`.`entity_id` DESC, `name` DESC LIMIT 9

And both didn't order product correctly. Ony works with price:

... ORDER BY `price_index`.`min_price` desc, `e`.`entity_id` DESC LIMIT 9

What coul it be? How can I resolve this problem?

Thanks!

UPDATE: After some research in Magento code, I detected that the entity_id field is added to ORDER BY segment in Magento\CatalogSearch\Model\ResourceModel\Fulltext::_renderFiltersBefore, exactly here:

/**
     * @inheritdoc
     */
    protected function _renderFiltersBefore()
    {
        ...

        /*
         * This order is required to force search results be the same
         * for the same requests and products with the same relevance
         * NOTE: this does not replace existing orders but ADDs one more
         */
        $this->setOrder('entity_id');

        return parent::_renderFiltersBefore();
    }

This code segment is only in Magento 2.2.2, I don´t know if is present in 2.2.1 or 2.2.0 but is not in 2.1.7 at least.

Anyway, the comment says that "this does not replace existing orders but ADDs one more", but the true is that this order field is added BEFORE my main order field (before name, before position, before my custom attribute). So, I guess this function is running before the chosen field is added, and therefore it first ordered by the entity_id. But here my question would be: is this normal and then would it be a Magento bug? Or is it not something normal and then could there be something at code level, either of the theme or of some extension, that is causing it?

What do you think? What could I check next?

Best Answer

Apparently this is a bug of the version 2.2.2. I found the fix here:

https://github.com/magento/magento2/commit/e5b030afbfa1714763f640b36509230230ec0c1f

After apply this patch, the products ordered correctly. The fix, from what I've read, will be part of 2.2.4 version.

Related Topic