Filtering a Magento 2 Object Repository
Check out the following sample class. To filter by SKU, try this:
$productFilterDemo->getProducts('sku', 'product_sku_value', 'eq');
To get products created after specific date, this:
$productFilterDemo->getProducts('created_at', 'creation date', 'gt');
Sample class:
<?php
namespace Vendor\ModlueName\Model;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ProductFilterDemo
{
/** @var ProductRepositoryInterface */
protected $productRepository;
/** @var SearchCriteriaBuilder */
protected $searchCriteriaBuilder;
/**
* Initialize dependencies.
*
* @param ProductRepositoryInterface $productRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* Get products with filter.
*
* @param string $fieldName
* @param string $fieldValue
* @param string $filterType
* @return \Magento\Catalog\Api\Data\ProductInterface[]
*/
public function getProducts($fieldName, $fieldValue, $filterType)
{
$searchCriteria = $this->searchCriteriaBuilder->addFilter($fieldName, $fieldValue, $filterType)->create();
$products = $this->productRepository->getList($searchCriteria);
return $products->getItems();
}
}
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
FilterBuilder $filterBuilder,
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->filterBuilder = $filterBuilder;
}
public function getProducts()
{
$filters[] = $this->filterBuilder
->setField('sku')
->setConditionType('eq')
->setValue('something')
->create();
$this->searchCriteriaBuilder->addFilters($filters);
$searchCriteria = $this->searchCriteriaBuilder->create();
$searchResults = $this->productRepository->getList($searchCriteria);
return $searchResults->getItems();
}