In Magento 2, can you use a product repository to filter by product attributes?
In Magento 2, you can use a search criteria object
\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria,
and a repository
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
To fetch a list of objects
$searchCriteria->getPageSize(10);
$list = $productRepository->getList($searchCriteria);
However, the searchCriteria object doesn't (seem to?) have direct filtering capabilities. The search criteria class does have methods for adding something called filterGroups
#File: lib/internal/Magento/Framework/Api/SearchCriteria.php
public function getFilterGroups()
{
$filterGroups = $this->_get(self::FILTER_GROUPS);
return is_array($filterGroups) ? $filterGroups : [];
}
public function setFilterGroups(array $filterGroups = null)
{
return $this->setData(self::FILTER_GROUPS, $filterGroups);
}
But it's not clear what, exactly, a filter group is thanks to PHP's untyped arrays.
How can I use a Magento 2 repository to do things like
- Show me all the products with [this specific SKU]
- Show me all the products created after [this date]
- etc.
Best Answer
Check out the following sample class. To filter by SKU, try this:
To get products created after specific date, this:
Sample class: