7

Is there any chance to reload collection in Magento 2?

For example:


foreach($items as $singleItems){
    $collection = $this->_myCollection->addFieldToFilter('filed', $singleItems->something);
...
}

For each iteration i need clear collection and load one more time.

13

To clear a collection you can call:

$this->_myCollection->clear();

To reload a collection you can call:

$this->_myCollection->load();
  • 5
    Note that load without a previous clear does nothing if the collection was already loaded. – Fabian Schmengler Aug 30 '16 at 7:27
  • 1
    @fschmengler totally you usually see both lines one after the other when a reload is needed – Raphael at Digital Pianism Aug 30 '16 at 7:28
  • 2
    Perhaps you should add a full example to the answer: foreach($items as $singleItems){ $collection = $this->_myCollection ->clear() ->addFieldToFilter('filed', $singleItems->something) ->load(); } – Siarhey Uchukhlebau Aug 30 '16 at 7:41
0

you can use CollectionFactory instance Collection. the factory class by creating method every time create a fresh object without recent data

  • yes but you don't want to keep creating objects especially in a loop, unless there is a case where the class is reusing the existing object behind the scenes. – NathanielR Aug 14 at 16:31
6

If you applied filters, you can reset collection with :

$this->_myCollection->clear()->getSelect()->reset(\Zend_Db_Select::WHERE);

Then :

$this->_myCollection->addFieldToFilter('field', $singleItems->getSomething());
$this->_myCollection->load();
  • 1
    This is worked like charm. upvoted (Y) Thanks :) – Ashish Raj Mar 5 at 14:19

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.