How to Apply OR Conditions To Collection In Magento 2

You can use OR & AND condition to collection in magento 2

For AND Condition

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']]);

For OR Condition

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']]);

OR CONDITION for addFieldToFilter filter

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']]
);
If you are looking for Magento Developers, visit Magento Developer Agency.
Related Products