Magento 2 - addFieldToFilter Collection with OR condition

Today we are going to cover how to add OR condition with addFieldToFilter Collection in Magento 2. We had a requirement in our Free Shipping Bar module to show free shipping bar either when “from date” was selected by administrator or when “from date” was set to NULL or not selected. In both cases, we had to show free shipping bar on the frontend.

Anyways let’s crack on with code to see working examples with date filters using same attribute and other filters using different attributes.

 $this->_getCollection()->addFieldToFilter( ['attribute_1','attribute_2'], [ ['lteq' =>value], ['null'=>value] ]
); 

Using the above code, we are going to add date filter with either today’s date or null

 $this->_getCollection()->addFieldToFilter( ['from_date','from_date'], [ ['lteq' => $this->_localeDate->date()->format('Y-m-d')], ['null'=>true] ]
);

This should show something like below in your query

((`from_date` <= '2019-06-25') OR (`from_date` IS NULL))

Please see another example with different attributes -:

 $this->_getCollection()->addFieldToFilter(['color', 'size', 'country'], [ ['eq' => 'yellow'], ['eq' => '10'], ['neq' => 'GB'] ]);

This should show something like below in your query

((`from_date` = 'yellow') OR (`size` = '10) OR (`country` != 'GB))

Add blank or null filter with your Magento 2 collection

 $this->_getCollection()->addFieldToFilter(['shipping_description'], [ ['eq' => ""], ['eq' => '0'], ['null' => true] ]);

This should show something like below in your query

((`shipping_description ` = '') OR (`shipping_description ` = '0') OR (`shipping_description ` is null))

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts