Magento2 | PWA | GraphQL

Get Collections with SearchCriteriaBuilder and addFilters in Magento 2


Magento 2 uses SearchCriteriaBuilder to add search criteria while fetching the records.

What are the Search Criteria?

“Search Criteria” to search/filter the desired result from a repository.

What is Search Criteria Builder?

Search Criteria Builder helps us to build our search criteria. Basically, Search Criteria Builder is a class instance of what we need to search for. In order to use it, we need Search Criteria Interface. For that add its dependency to our class.

Filter:

Filters help to create search criteria filters we can set the field, its condition, and its value on the basis of which we want to filter/search the repository.

To get collections with SearchCriteriaBuilder in Magento 2, you can follow these steps:

1. Inject the Magento\Framework\Api\SearchCriteriaBuilder class in your constructor.

protected $searchCriteriaBuilder;

public function __construct(
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
}

2. Set the search criteria using the addFilter() method of SearchCriteriaBuilder class:

$this->searchCriteriaBuilder->addFilter('field_name', 'field_value');
Note: You can add multiple filters to the search criteria by calling addFilter() multiple times.

3. Build the search criteria using the create() method of SearchCriteriaBuilder class:

$searchCriteria = $this->searchCriteriaBuilder->create();

4. Retrieve the collection using the get() method of the repository interface:

$collection = $this->repository->getList($searchCriteria);

Note: Where $repository is the instance of the repository interface for the entity you want to retrieve.

Let’s see an example of complete code:

<?php
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;
class testClass
{
    protected $searchCriteriaBuilder;
    protected $productRepository;
    public function __construct(
        SearchCriteriaBuilder $searchCriteriaBuilder,
        ProductRepositoryInterface $productRepository
    ) {
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->productRepository = $productRepository;
    }
    public function getProductCollection()
    {
        $this->searchCriteriaBuilder->addFilter('status', 1);
        $this->searchCriteriaBuilder->addFilter('visibility', [2, 3], 'in');
        $searchCriteria = $this->searchCriteriaBuilder->create();
        $products = $this->productRepository->getList($searchCriteria)->getItems();
        return $products;
    }
}

In the above example, we are using them ProductRepositoryInterface to retrieve a collection of products.

We are adding two filters to the search criteria using the addFilter() method of the SearchCriteriaBuilder class. The first filter filters products by their status, and the second filter filters products by their visibility.

The create() method is called on the SearchCriteriaBuilder object to create the search criteria object.

Then finally, we call the getList() method of ProductRepositoryInterface to retrieve the product collection that matches the search criteria.

To perform a multiple filter search in Magento 2 using the AND operator, you can use the following code:

$searchCriteria = $this->searchCriteriaBuilder
                ->addFilter('attribute_code1', 'value1')
                ->addFilter('attribute_code2', 'value2')
                ->create();

In this code, attribute_code1 and attribute_code2 are the attribute codes we want to filter by, and value1 and value2 are the values we want to filter for those attributes. We can add as many filters as you need by calling addFilter() multiple times.

To perform a multiple filter search in Magento 2 using the OR operator:

We need to add a class dependency to our constructor.

\Magento\Framework\Api\FilterBuilder $filterBuilder

Using FilterBuilder, we can add our filters to perform OR operations.

Check Below code:

/**
 * Find slides with is_active set to 0, that should be visible based on dates range, and activate those
 *
 * @return array IDs of sliders that were modified
 */
private function activateSlides(): array
{
    $sliderIds = [];

    $this->searchCriteriaBuilder
            ->addFilter(SlideInterface::IS_ACTIVE, 0);

    $currentDate = $this->timezone->date();
    $currentDate->setTimezone(
        new DateTimeZone('UTC')
    );
    $today = $currentDate->format(DateTime::DATETIME_PHP_FORMAT);

    $this->searchCriteriaBuilder
            ->addFilter(SlideInterface::DATE_FROM, $today, 'lteq');

    // filter group with OR inside
    $filter = $this->filterBuilder->setField(SlideInterface::DATE_TO)
        ->setConditionType('gteq')
        ->setValue($today)
        ->create();

    $filter2 = $this->filterBuilder->setField(SlideInterface::DATE_TO)
        ->setConditionType('null')
        ->setValue(true)
        ->create();

    $this->searchCriteriaBuilder
        ->addFilters([$filter, $filter2]);

    $slides = $this->slideRepository
        ->getList($this->searchCriteriaBuilder->create());

    if ($slides->getTotalCount() === 0) {
        return $sliderIds;
    }

    /** @var SlideInterface $slide */
    foreach ($slides->getItems() as $slide) {
        $slide->setIsActive(true);
        $this->slideRepository->save($slide);

        $sliderIds[] = (int)$slide->getSliderId();
    }

    return $sliderIds;
}

If we want to set filters AND/OR combinations then we will add another class FilterGroupBuilder. which combines the different filters into a single array.

\Magento\Framework\Api\Search\FilterGroupBuilder $filterGroupBuilder

Let’s check the example

// 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);

By the above code, the following query will generate.

attribute1 = 'value1' AND attribute2 = 'value2' AND (attribute3='value3' OR attribute4 = 'value4')

That’s it. These are the simple steps to get collections with SearchCriteriaBuilder in Magento 2 and how we can get collections using multiple filters in SearchCriteria.




Tag : Magento2
0 Comments On "Get Collections with SearchCriteriaBuilder and addFilters in Magento 2"

Back To Top