2

For now, I'm getting my best sales like this. I would like to be able to influence the order of my products in the collection.

In my Block :

use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory;
// ...
public function __construct(Template\Context $context,CollectionFactory $bestSellersCollectionFactory)
{
    $this->bestSellersCollectionFactory = $bestSellersCollectionFactory;
    parent::__construct($context, []);
}

public function getBestSellersProducts()
{
    $collection = $this->bestSellersCollectionFactory->create()->setModel(
        'Magento\Catalog\Model\Product'
    )
    ;

    return $collection;
}
// ...

In my template :

$collection = $block->getBestSellersProducts();
// improvised part that doesn't work
$collection->setPeriod('month')->setOrder('period','DESC')->load();
// result data period -> 2015,2016,2017,2018,2019...

The problem is that these products arrive in a chronologically increasing way and I would like the opposite of course :)

  • 1
    Have you tried doing $collection->getSelect()->order('period DESC')? Looking in the Bestsellers collection class it looks like that's how it sets the sort order, so that might override it. – rain2o Apr 8 at 16:26
1

You can override this method in this class : Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory

/**
 * Make select object for date boundary
 *
 * @param string $from
 * @param string $to
 * @return \Magento\Framework\DB\Select
 */
protected function _makeBoundarySelect($from, $to)
{
    $connection = $this->getConnection();
    $cols = $this->_getSelectedColumns();
    $cols[$this->getOrderedField()] = 'SUM(' . $this->getOrderedField() . ')';
    $select = $connection->select()->from(
        $this->getResource()->getMainTable(),
        $cols
    )->where(
        'period >= ?',
        $from
    )->where(
        'period <= ?',
        $to
    )->group(
        'product_id'
    )->order(
        $this->getOrderedField() . ' DESC' // 'period DESC'
    )->limit(
        $this->_ratingLimit
    );

    $this->_applyStoresFilterToSelect($select);

    return $select;
}

Or you can try this

$collection->setPeriod('month')->getSelect()->order('period DESC');

Good luck !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.