Magento 2:如何按商店ID过滤产品集合

时间:2016-11-24 17:39:59

标签: magento magento-2.0.7

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

我为每个品牌在一个网站下创建了不同的商店,并为每个品牌创建了不同的网址。所以,我想为每个品牌商店展示明智的产品品牌。

那么,按属性即品牌过滤产品的最简单方法之一。

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

使用此代码按商店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;
 }

答案 2 :(得分:0)

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;
    }
相关问题