I have 50k products in my website and want to update tier price. I have existing tier prices for products, but based on the existing product price, I need to update customer price.

I have created an external root file and created one function. Like in Magento 1 I did:

$products = Mage::getModel('catalog/product')
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToSort('created_at', 'desc'); 

        array(array($this, '_Callback')),

I want to do the same thing in Magento 2m using a collection. I want to only call _Callback function with Magento 2 product collection so that it can work collection walk iteratively.

$productCollection = $objectManager

$productcollection = $productCollection

Please give me solution.


This is just an example code, please inject correct repositories and models


use Magento\Framework\Model\ResourceModel\Iterator;
use Magento\Framework\Model\ResourceModel\IteratorFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactoryInterface;
use Zend_Db_Select;

class RunSomeLongTask
    public const ORDER_STATE_VALUE = 'example';

    /** @var CollectionFactoryInterface  */
    private $orderCollectionFactory;

    /** @var IteratorFactory */
    private $iteratorFactory;

    /** @var SomeTask */
    private $someTask;

     * constructor.
     * @param CollectionFactoryInterface $orderCollectionFactory
     * @param IteratorFactory $iteratorFactory
     * @param SomeTask $someTask
    public function __construct(
        CollectionFactoryInterface $orderCollectionFactory,
        IteratorFactory $iteratorFactory,
        SomeTask $someTask
    ) {
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->iteratorFactory = $iteratorFactory;
        $this->someTask = $someTask; // "important: remember create this class"

    public function process(): void
        $orderCollection = $this->orderCollectionFactory->create();

            ->columns(['entity_id', 'state', 'status'])
            ->where('state=?', self::ORDER_STATE_VALUE);

        /** @var Iterator $iterator */
        $iterator = $this->iteratorFactory->create();

        $iterator->walk($orderCollection->getSelect(), [[
            $this->someTask, // instance of class SomeTask
            'run' // the function in your class "SomeTask"

class SomeTask
    public function run(array $args): void
        // you will receive the row data here
        $orderId = $args['row']['entity_id'];

        // do your task here on individual row


  • Thanks for your reply. how to use for products collection and root of magento file.can you please give me examples for product collection with root external file. Sep 28 '20 at 6:35

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.