简体   繁体   中英

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 ie brand.

I am using Magento 2.1.2, MySQL 6, PHP 7.0

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');

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;
 }
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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM