Get Collection Using SearchCriteriaBuilder in Magento 2

Magento 2 strongly insist developers to use Repositories to perform CRUD operations. In the previous article, we have seen the use of a service contract to avoid the use of getCollection method. The service contract is a part of the repository design pattern and the repository uses SearchCriteriaBuilder to fetch records.

SearchCriteriaBuilder is widely used in the core code of Magento 2. However, many developers don’t know how to use SearchCriteriaBuilder to get the records. Today we will see how to get collection using SearchCriteriaBuilder in Magento 2.

Get Collection Using SearchCriteriaBuilder

For example, you would like to get a collection of a custom table inside your block file, you can use the below code.

<?php
namespace CodextblogDemoBlock;

use MagentoFrameworkViewElementTemplate;
use MagentoFrameworkViewElementTemplateContext;
use MagentoFrameworkApiSearchCriteriaBuilder;
use MagentoFrameworkApiSortOrderBuilder;
use CodextblogDemoApiFeatureRepositoryInterface;

class Test extends Template
{

  /**
  * @var SearchCriteriaBuilder
  */
  protected $searchCriteriaBuilder;

  /**
  * @var SortOrderBuilder
  */
  protected $sortOrderBuilder;

  /**
  * @var FeatureRepositoryInterface
  */
  protected $featureRepository;

  public function __construct(
        Context $context,
      	SearchCriteriaBuilder $searchCriteriaBuilder,
        SortOrderBuilder $sortOrderBuilder,
      	FeatureRepositoryInterface $featureRepository,
    ) {
       	$this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->sortOrderBuilder = $sortOrderBuilder;
       	$this->featureRepository = $featureRepository; 
        parent::__construct($context);
  }

  public function getRecords($productId){

  	$searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('product_id', $productId, 'eq');

    $searchCriteria = $searchCriteria->create();
    $searchResult = $this->featureRepository->getList($searchCriteria);
    if ($searchResult->getTotalCount() > 0) {
    	$items = $searchResult->getItems();
    	echo "<pre>";
    	print_r($items);
    	die;
    }
  }
}

Here you can see we have used getList method of featureRepository. FYI featureRepository should be created as part of the service contract in your module. Otherwise, you can not use SearchCriteriaBuilder.

SearchCriteriaBuilder In Clause

<?php
$skus = explode(',', $skus);

$searchCriteria = $this->searchCriteriaBuilder
->addFilter('sku', $skus, 'IN');

$searchCriteria = $searchCriteria->create();

$searchResult = $this->productRepository->getList($searchCriteria);

if ($searchResult->getTotalCount() > 0) {
	$items = $searchResult->getItems();
	foreach ($items as $item) {
		  echo $item->getId();
	}
}

SearchCriteriaBuilder Sort Order

<?php
$sortOrder = $this->sortOrderBuilder->setField('entity_id')->setDirection('DESC')->create();
$searchCriteria = $this->searchCriteriaBuilder->setSortOrders([$sortOrder]);
$searchCriteria = $searchCriteria->create();

$searchResult = $this->productRepository->getList($searchCriteria);

You can read more about the service contract and SearchCriteriaBuilder on the official Magento 2 devdocs page. I hope this article will help you. Feel free to write in the comment section if you have any queries.

Written by

Chirag

Chirag is a Founder & eCommerce Technology Leader at MageArmy. He leads the eCommerce development team and drives the company’s technology vision, helping businesses build, scale, and optimize high-performing online stores. With years of experience in eCommerce development, he has worked with businesses across industries to solve complex technical challenges and create scalable digital commerce solutions. He loves sharing practical insights about eCommerce development, Magento, Adobe Commerce, and the latest trends in digital commerce to help online businesses grow and succeed.