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.

namespace Codextblog\Demo\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Codextblog\Demo\Api\FeatureRepositoryInterface;

class Test extends Template

  * @var SearchCriteriaBuilder
  protected $searchCriteriaBuilder;

  * @var FeatureRepositoryInterface
  protected $featureRepository;

  public function __construct(
        Context $context,
      	SearchCriteriaBuilder $searchCriteriaBuilder,
      	FeatureRepositoryInterface $featureRepository,
    ) {
       	$this->searchCriteriaBuilder = $searchCriteriaBuilder;
       	$this->featureRepository = $featureRepository; 

  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>";

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.

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.

Want to ask a question or leave a comment?

Leave a Comment


All the comments are goes into moderation before approval. Please do not spam. Your email address will not be published. Required fields are marked *

Enjoy this post? Please support Us!

Follow us on twitter for daily new updates..


Want to become
a Magento 2 Expert?

If Yes! Then Subscribe to our newsletter and get weekly article to you email id.
Subscribe Here

To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.