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.

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', array('like' => '24MB%'));
$collection->addAttributeToFilter('type_id', array('eq' => 'simple'));

Output:
SELECT `e`.* FROM `catalog_product_entity` AS `e` WHERE (`e`.`sku` LIKE ’24MB%’) AND (`e`.`type_id` = ‘simple’); Continue reading “How to apply OR conditions to collection in Magento 2?”

Direct SQL Query in Magento 2

There are many situations where executing direct raw SQL queries would be simple and much quicker leading to a more optimized Magento get collection query as a performance basis.

On a large data set of an entity, Saving each individual entity can take a long time with resource-hungry and therefore make the system unusable.

Overcome this issue it is possible to issue a direct SQL query that could update a large set of data of an entity in fewer seconds.

When you use Direct SQL Query you don’t need to worry about Model/Factory Pattern. Continue reading “Direct SQL Query in Magento 2”