Third Party Platform interact with Magento 2 by API. When you are working for API related stuff and using SearchCriteriaBuilder Object for your query and if you want to apply OR conditions for custom query, You need to define setFilterGroups([Object]) for OR query.
Whenever you are dealing with SearchCriteriaBuilder in Magento 2, You might be need to query with OR conditions for custom requirement, You can give OR conditions to Magento\Framework\Api\SearchCriteriaBuilder by simple code snippets.
Let’s imagine, We built a query using OR conditions for Products.
Fetch collection of only those products whose sku is like `MSH01%` OR `type_id` is equal to simple.
<?php namespace Rbj\Training\Block; class Training extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, \Magento\Framework\Api\FilterBuilder $filterBuilder, \Magento\Framework\Api\Search\FilterGroupBuilder $filterGroupBuilder, array $data = [] ) { $this->customerRepository = $customerRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->filterBuilder = $filterBuilder; $this->filterGroupBuilder = $filterGroupBuilder; parent::__construct($context, $data); } /** * OR condition for searchCriteriaBuilder */ public function applyOrCondition() { $filter_1 = $this->filterBuilder ->setField('sku') ->setConditionType('like') ->setValue('MSH01%') ->create(); $filter_2 = $this->filterBuilder ->setField('type_id') ->setConditionType('eq') ->setValue('simple') ->create(); $filter_group = $this->filterGroupBuilder ->addFilter($filter_1) ->addFilter($filter_2) ->create(); // add filter group to setFilterGroups() $searchCriteria = $this->searchCriteriaBuilder ->setFilterGroups([$filter_group]) ->create(); $products = $this->productRepository->getList($searchCriteria)->getItems(); return $products; }
Using Magento\Framework\Api\FilterBuilder class, You need to create filterBuilder for your separate field.
using Magento\Framework\Api\Search\FilterGroupBuilder class, apply AND conditions to addFilter( ) with filterGroupBuilder object.
Now Our searchCriteriaBuilder instance is ready for fetch collection of products,
$products = $this->productRepository->getList($searchCriteria)->getItems();
gives the result of our OR query for a products.
Refer for Custom Collection OR conditions by, Apply OR condtions for Collection in Magento 2