Reading list Switch to dark mode

    Get Collections with SearchCriteriaBuilder in Magento 2

    Updated 29 April 2023

    In this post, we will explore how to get collections with SearchCriteriaBuilder in Magento 2. Although this is widely utilized in Magento 2’s core code, it remains unfamiliar to many developers.

    Magento 2 strongly insists developers use Repositories to perform CRUD operations and the repository uses SearchCriteriaBuilder to fetch 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.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    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.

    $searchCriteria = $this->searchCriteriaBuilder->addFilters([
        $this->filterBuilder
            ->setField('attribute_code1')
            ->setValue('value1')
            ->create(),
        $this->filterBuilder
            ->setField('attribute_code2')
            ->setValue('value2')
            ->create()
    ])->create();

    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.

    You may like other posts:

    Advanced Pricing in Magento2

    Understanding Magento Theme: Customize Theme (Child-Theme-Concept)

    Thanks & Happy Coding !!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home