How to apply OR conditions to collection in Magento 2?

In Magento 2, You can apply OR conditions on collection. By default, When you work with collection, Your conditions will be AND.

AND Condition
Fetch collection of only those products whose sku is like 24MB% AND type_id is equal to simple.

Output:
SELECT e.* FROM catalog_product_entity AS e WHERE (e.sku LIKE ’24MB%’) AND (e.type_id = ‘simple’);

Using above collection you have applied AND conditions and query will be AND relation.

OR CONDITION:
When You want to apply OR conditions on collection, You need to do like below way,
Fetch collection of only those products whose sku is like 24MB% OR type_id is equal to simple.

OR CONDITION for addAttributeToFilter filter:

Output:
SELECT e.* FROM catalog_product_entity AS e WHERE ((e.sku LIKE ’24MB%’) OR (e.type_id = ‘simple’))

Now addFieldToFilter with OR Condition in Magento 2,
OR CONDITION for addFieldToFilter filter:

Output:
SELECT main_table.* FROM sales_order AS main_table WHERE ((customer_is_guest = 1) OR (status = ‘pending’));
customer_is_guest and status is not an attribute value. Its system defined field.

One Reply to “How to apply OR conditions to collection in Magento 2?”

Leave a Reply

Your email address will not be published. Required fields are marked *