Hello Magento Friends,
In this tutorial, I will be describing How to Apply OR Conditions to Collection in Magento 2.
Collection in Magento 2 is used to retrieve objects of the same category like product collection, customer collection, categories, etc. AND and OR are the Magento 2 collection conditions that can be applied to retrieve product data from the collection in Magento. AND is the default Magento 2 collection conditions.
In this tutorial, we will learn about Magento 2 addFieldToFilter and addAttributeToFilter OR conditions.
Steps to Apply OR Conditions to Collection in Magento 2:
Step 1: Apply OR condition for Magento 2 addAttributeToFilter collection
protected $_productCollection;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection)
{
$this->_productCollection = $productCollection;
}
public function getProductCollection()
{
$this->_productCollection->addAttributeToFilter(array(
array(
'attribute' => 'sku',
'like' => '24MB%’),
array(
'attribute' => 'type_id',
'eq' => 'simple')
));
echo $this->_productCollection->getSelect();
}Output:
SELECT `e`.* FROM `catalog_product_entity` AS `e` WHERE ((`e`.`sku` LIKE '24MB%') OR (`e`.`type_id` = 'simple'))
Step 2: Apply OR condition for Magento 2 addFieldToFilter collection
protected $_orderCollection;
public function __construct(
\Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection)
{
$this->_orderCollection = $orderCollection;
}
public function getOrderCollection()
{
$this->_orderCollection->addAttributeToFilter(array(
array(
'attribute' => 'sku',
'like' => '24MB%’),
array(
'attribute' => 'type_id',
'eq' => 'simple')
));
echo $this->_orderCollection->getSelect();
}Output:
SELECT `main_table`.* FROM `sales_order` AS `main_table` WHERE ((`customer_is_guest` = 1) OR (`status` = 'pending'))
Conclusion:
Accordingly, you can apply OR conditions for addAttributeToFilter and addFieldToFilter Magento 2. If you have any doubt about the addAttributeToFilter and addFieldToFilter Magento 2 collection conditions, freely contact me through the comment part. Share the article with your friends and keep yourself updated with the latest Magento solutions by us.
Happy Coding!






