Magento 2: How to Filter a Product Collection By Store ID
You can do this with the method addStoreFilter()
, see Magento\Catalog\Model\ResourceModel\Product\Collection#addStoreFilter()
the addStoreFilter()
function will accept store ID or Store
object as a parameter.
EG, to get all products for the current store:
public function getProducts(){
return $this->collection->addStoreFilter($this->_storeManager->getStore());
}
Hopefully, this helps.
For now this looks like a bug, because there is no possibility to apply store filter with the ProductRepository::getList()
method, passing store id as a filter of SearchCriteria.
In the getList implementation, you can find that all the filters from SearchCriteria applied to collection
foreach ($searchCriteria->getFilterGroups() as $group) {
$this->addFilterGroupToCollection($group, $collection);
}
In Magento\Catalog\Model\ProductRepository::addFilterGroupToCollection
there is special handling for Category filter, but there is no one for Store.
So, additional condition should be added to Magento\Catalog\Model\ProductRepository::addFilterGroupToCollection
which checks whether we have store filter and if we have - set store id for collection, something like:
if ($filter->getField() == \Magento\Catalog\Model\Product::STORE_ID) {
$collection->setStore($filter->getValue());
continue;
}
Created internal bug for this issue, its number is MAGETWO-45950