Magento2: How to add multiple AND and OR conditions to filter/filterGroups?
Yes it is possible
You can create an
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
\Magento\Framework\Api\FilterBuilder $filterBuilder
\Magento\Framework\Api\Search\FilterGroupBuilder $filterGroupBuilder
After that define your filters
// AND
$this->searchCriteriaBuilder->addFilter('attribute1','value2');
$this->searchCriteriaBuilder->addFilter('attribute2','value2');
// OR
$attr3 = $this->filterBuilder->setField('attribute3')
->setValue('value3')
->setConditionType('eq')
->create();
$attr4 = $this->filterBuilder->setField('attribute4')
->setValue('value4')
->setConditionType('eq')
->create();
$filterOr = $this->filterGroupBuilder
->addFilter($attr3)
->addFilter($attr4)
->create();
$this->searchCriteriaBuilder->setFilterGroups([$filterOr]);
$searchCriteria = $this->searchCriteriaBuilder->create();
$this->productRepository->getList($searchCriteria);
GET ==>
attribute1 = 'value1' AND attribute2 = 'value2' AND (attribute3='value3' OR attribute4 = 'value4')
Tell me if you have any other questions
$attr1 = $this->filterBuilder->setField('attribute1')
->setValue('value1')
->setConditionType('eq')
->create();
$attr2 = $this->filterBuilder->setField('attribute2')
->setValue('value2')
->setConditionType('eq')
->create();
$filterOr1 = $this->filterGroupBuilder
->addFilter($attr1)
->addFilter($attr2)
->create();
$attr3 = $this->filterBuilder->setField('attribute3')
->setValue('value3')
->setConditionType('eq')
->create();
$attr4 = $this->filterBuilder->setField('attribute4')
->setValue('value4')
->setConditionType('eq')
->create();
$filterOr2 = $this->filterGroupBuilder
->addFilter($attr3)
->addFilter($attr4)
->create();
$this->searchCriteriaBuilder->setFilterGroups([$filterOr, $filterOr2]);
$searchCriteria = $this->searchCriteriaBuilder->create();
$this->productRepository->getList($searchCriteria);
GET ==>
(attribute1 = 'value1' OR attribute2 = 'value2') AND (attribute3='value3' OR attribute4 = 'value4')