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 Codextblog\Demo\Block;

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

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.

Want to ask a question or leave a comment?

Leave a Comment

(0 Comments)

All the comments are goes into moderation before approval. Irrelevant comment with links directly goes to spam. Your email address will not be published.

Was this post helpful? Please support Us!

Follow us on twitter or Like us on facebook.

 


To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close

Increase Your
Magento 2
Knowledge

Get Weekly Tutorial
to your Inbox
Subscribe Me
close-link
Subscribe Here