繁体   English   中英

Magento 2:如何通过商店ID筛选产品集合

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

我正在尝试展示特定品牌的产品。 品牌是我的强制属性之一,每个产品都附有该属性。

我在一个网站下为每个品牌创建了不同的商店,还为每个品牌创建了不同的URL。 因此,我想为每个品牌商店展示产品品牌。

因此,按属性(即品牌)过滤产品的最简单方法。

我正在使用Magento 2.1.2,MySQL 6,PHP 7.0

使用以下代码按商店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');

使用此代码通过商店ID和属性代码过滤产品集合

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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