Magento - addStoreFilter not working?

前端 未结 4 2082
灰色年华
灰色年华 2020-12-18 09:10

When getting a product collection in Magento, I would expect the StoreFilter to do just that, filter by the current store. But I can\'t get it to work.

Say I have 2

相关标签:
4条回答
  • 2020-12-18 09:20

    $_testproductCollection should look like this $_testproductCollection = Mage::getResourceModel('reports/product_collection')->addAttributeToSelect('*')->addStoreFilter().

    If You print SELECT from that collection You will see that there ain't any store column, so addStoreFilter() can't apply WHERE.

    You should use joinField() on Your collection and add store_id column from catalog_product_entity_varchar table.

    EDIT

    Sorry to keep You waiting ;)

    $collection = Mage::getResourceModel('catalog/product_collection');
    $collection->joinField('store_id', 'catalog_category_product_index', 'store_id', 'product_id=entity_id', '{{table}}.store_id = 1', 'left');
    $collection->getSelect()->distinct(true);
    

    This should do the trick, but just to be sure, please check if you're getting right products :)

    0 讨论(0)
  • 2020-12-18 09:23

    I think

    You don't need to do any joins as the magento's setStoreId() will work.

     $collection = Mage::getModel("catalog/product")
    ->getCollection()
    ->setStoreId(1) //change store Id according your needs
    ->addAttributeToSelect(array('name','url','sku'))
    ->setPageSize(20);                
    

    This will get maximum 20 products from store id 1

    0 讨论(0)
  • 2020-12-18 09:28

    This worked for me:

    Mage::app()->setCurrentStore($storeId); 
    $productCollection = Mage::getModel('catalog/product')
                ->getCollection()
                ->addStoreFilter()
                ->addAttributeToSelect(array('sku','price'));
    
    0 讨论(0)
  • 2020-12-18 09:40

    OK, I think this works, haven't tested too much but seems to have done the trick. You need to first get your stores root category id, then join some fields so you have access to the products "category_id", then filter using that:

    $_rootcatID = Mage::app()->getStore()->getRootCategoryId();
    
    $_testproductCollection = Mage::getResourceModel('catalog/product_collection')
    ->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left')
    ->addAttributeToFilter('category_id', array('in' => $_rootcatID))
    ->addAttributeToSelect('*');
    $_testproductCollection->load();
    
    foreach($_testproductCollection as $_testproduct){ 
        echo $this->htmlEscape($_testproduct->getName())."<br/>"; 
    };
    
    0 讨论(0)
提交回复
热议问题