How to Apply OR Conditions To Collection In Magento 2
Magento 2 allows applying OR & AND conditions to collections in Magento 2. However, the default condition applied is AND to collections in Magento 2.
Example for AND Condition:
1 2 3 4 5 6 7 8 9 |
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; protected $productCollectionFactory; public function __construct(CollectionFactory $productCollectionFactory) { $this->productCollectionFactory = $productCollectionFactory; } $collection = $this->productCollectionFactory->create(); $collection->addAttributeToSelect('*'); $collection->addAttributeToFilter([['attribute'=>'sku','like'=>'%ch%'],['attribute'=>'status', 'eq'=>'1']]); |
The collection of only those products will be fetched whose (write according to the example)
SKU starts with mt and product type is simple
Example for OR Condition:
The method to apply OR conditions to collection in Magento 2 is as below:
OR CONDITION for addAttributeToFilter filter:
1 2 3 4 5 6 7 8 9 10 |
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; protected $productCollectionFactory; public function __construct(CollectionFactory $productCollectionFactory) { $this->productCollectionFactory = $productCollectionFactory; } $collection = $this->productCollectionFactory->create(); $collection->addAttributeToSelect('*'); $collection->addAttributeToFilter([['attribute'=>'sku','like'=> '%ch%'], ['attribute'=>'status','eq' => '1']]); |
SKU content character ch or status is 1
OR CONDITION for addFieldToFilter filter:
1 2 3 4 5 6 7 8 9 10 |
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; protected $productCollectionFactory; public function __construct(CollectionFactory $productCollectionFactory) { $this->productCollectionFactory = $productCollectionFactory; } $collection = $this->productCollectionFactory->create(); $collection->addAttributeToSelect('*'); $collection->addFieldToFilter(['attribute_set_id','type_id'],[['eq'=>4],['eq'=>'simple']] ); |
That’s it.
In this way, you can add OR conditions to the collection in Magento 2 using the addFieldToFilter() method.
Any doubts in the method can be mentioned in the Comments section below and I’d be glad to help you out.
Do share the post with Magento peeps via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
The Secret to Get Serialize Value in Array Format in Magento 2
Everything About search_query Table In Magento 2
Next