11

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.

3 Answers 3

19

To clear a collection you can call:

$this->_myCollection->clear();

To reload a collection you can call:

$this->_myCollection->load();
3
  • 5
    Note that load without a previous clear does nothing if the collection was already loaded. Commented Aug 30, 2016 at 7:27
  • 1
    @fschmengler totally you usually see both lines one after the other when a reload is needed Commented Aug 30, 2016 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(); } Commented Aug 30, 2016 at 7:41
11

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();
2
  • 1
    This is worked like charm. upvoted (Y) Thanks :)
    – Ashish Raj
    Commented Mar 5, 2019 at 14:19
  • 1
    This is the best answer, it worked nice! Commented Oct 30, 2020 at 19:23
0

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

1
  • 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
    Commented Aug 14, 2019 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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