Tushar Balwadkar
Tushar Balwadkar

Reputation: 21

Magento 2: How to Filter a Product Collection By Store ID

I am trying to display brand specific product. brand is one of my attribute which is mandatory and attached by each product.

I created different store under one website for each brand and also created different URL for each brand. so, i want to display product brand wise for each brand store.

So, which of the easiest way to filter product by attribute i.e brand.

I am using Magento 2.1.2, MySQL 6, PHP 7.0

Upvotes: 0

Views: 13801

Answers (3)

Vijay R
Vijay R

Reputation: 160

use this code to filter the product collection by store id and attribute code

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

protected $collectionFactory

public function __construct(CollectionFactory $collectionFactory)
{ 
  $this->collectionFactory =$collectionFactory; 
}

 public function productCollection($storeId ,$attributeCode)
 { 
  $collection = $collectionFactory->create();
  $collection->addAttributeToSelect('*')
  $collection->addStoreFilter($storeId) 
  $collection->addAttributeToFilter($attributeCode); 
  return $collection;
 }

Upvotes: 1

veronica
veronica

Reputation: 1

use Magento\Framework\Data\OptionSourceInterface;
class Productlist implements OptionSourceInterface{
    /**
    * Get products
    *
    * @return array
    */
    public function toOptionArray(){
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $store=$objectManager->create('\Magento\Store\Model\StoreRepository');
        $productCollectionFactory =$objectManager->create('\Magento\Catalog\Model\Product')->getCollection();
        $storeId='3';
        $productCollectionFactory->addAttributeToSelect('name');
        $rootCategoryId = $store->getById($storeId)->getRootCategoryId();
        $productCollectionFactory->addAttributeToSelect('*');
        $productCollectionFactory->addCategoriesFilter(array('eq' => $rootCategoryId));
        $options = [];
        foreach ($productCollectionFactory as $product) {
            $options[] = ['label' => $product->getName(), 'value' => $product->getId()];
        }
        return $options;
    }

Upvotes: 0

Abhinav Kumar Singh
Abhinav Kumar Singh

Reputation: 2325

Use the following code to Filter a Product Collection By Store ID:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*')
$collection->addStoreFilter($storeid)
$collection->addAttributeToFilter('attribute_code');

Upvotes: 4

Related Questions