Magento 2 have addFieldToFilter to apply conditions on collections. Here we will see how can we apply OR condition like (status
IS NULL) OR (status
= ‘complete’) with the help of addFieldToFilter method.
Check out the below code to understand the syntax,
$this->customFactory->create() ->getCollection() ->addFieldToFilter( ['status', 'status'], [ ['null' => true], ['eq' => 'complete'] ] );
Now let’s consider a more complicated with multiple OR conditions, like given below,
( (`start_date` >= '2020-01-01') OR (`end_date` < '2020-01-31') OR ( ( (`status` IS NULL) OR (`status` = 'complete') ) ) )
Now let’s see the code in Magento 2 to implement this condition,
$this->customFactory->create() ->getCollection() ->addFieldToFilter( ['start_date', 'end_date', 'status'], [ ['gteq' => '2020-01-01'], ['lt' => '2020-01-31'], [ ['null' => true], ['eq' => 'complete'] ] ] );
Thanks for reading this blog. Feel free to comment if you face any issue.
Happy Coding