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.
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'))
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!
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…
The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…