Magento – Magento2.2.x How to remove a field filter from collection

filtermagento2magento2.2

I am loading a collection:

$model = $this->_objectManager->create('Test\Demo\Model\Book');
$collection = $model->getCollection();
$data = [regionCode => 111,regionCode=>222];
foreach ($data as $address) {
$collection->addFieldToFilter(
            'region', array(
                'eq' => $address['regionCode']
            )
        );
    if($collection->getSize()){ /* ex - 111 region available and 222 is not so both time collection getSize() - 1 */
       $model->setData('region',$address['regionCode']);
       $model->save();
       $collection->getSelect()->reset(\Magento\Framework\DB\Select::WHERE);
    }
}

How can I remove this (or all) filter from the collection again? I don't want to load a new collection every time the filter changes.

I tried also

$collection->resetData();

But that doesn't seem to have any effects on the filter.

Best Answer

Try this

protected $bookFactory;
public function __construct(..., Test\Demo\Model\BookFactory $bookFactory, ...) {
    $this->bookFactory = $bookFactory;
}

public function yourFunction() {
    $data = [regionCode => 111,regionCode=>222];
    foreach ($data as $address) {
    $colllection = $this->bookFactory->create()->getCollection();
    $result = $collection->addFieldToFilter(
                    'region', array(
                        'eq' => $address['regionCode']
                    )
                );
        if(count($result)){ /* ex - 111 region available and 222 is not so both time collection getSize() - 1 */
           $model->setData('region',$address['regionCode']);
           $model->save();
           $collection->getSelect()->reset(\Magento\Framework\DB\Select::WHERE);
        }
    }
}

Try to create singleton, might help you. lets know the result so that we can help more on this.

Related Topic