Is there a way to get all products by a specific attribute value? For example: how can I get all the products where the attribute color is red?
1 Answer
You can use below code
class GetProducts{
protected $_productRepository;
protected $_searchCriteriaBuilder;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->_productRepository = $productRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
}
public function getProductCollection(){
$searchCriteria = $this->_searchCriteriaBuilder->addFilter('color', 4, 'eq')->create(); // 4 is the option id, may be red/green/blue, check in admin
$searchResults = $this->_productRepository->getList($searchCriteria);
$productsIds = $searchResults->getItems();
return $productsIds;
}
Hope this may help you