2011-11-24 172 views
1

我想獲得至少有一個類別的產品集合。其實我想忽略那些不屬於任何類別的產品。誰能幫助嗎? 我的代碼如下:Magento:獲得至少有一個類別的產品集合

protected function _prepareCollection() 
{ 
    $store = $this->_getStore(); 
    $collection = Mage::getModel('catalog/product')->getCollection() 
     ->addAttributeToSelect('sku') 
     ->addAttributeToSelect('name') 
     ->addAttributeToSelect('attribute_set_id') 
     ->addAttributeToSelect('type_id') 
     ->joinField('qty', 
      'cataloginventory/stock_item', 
      'qty', 
      'product_id=entity_id', 
      '{{table}}.stock_id=1', 
      'left'); 

    if ($store->getId()) { 
     //$collection->setStoreId($store->getId()); 
     $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID; 
     $collection->addStoreFilter($store); 
     $collection->joinAttribute('name', 'catalog_product/name', 'entity_id', null, 'inner', $adminStore); 
     $collection->joinAttribute('custom_name', 'catalog_product/name', 'entity_id', null, 'inner', $store->getId()); 
     $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner', $store->getId()); 
     $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner', $store->getId()); 
     $collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $store->getId()); 
    } 
    else { 
     $collection->addAttributeToSelect('price'); 
     $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner'); 
     $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner'); 
    } 

    $this->setCollection($collection); 

    parent::_prepareCollection(); 
    $this->getCollection()->addWebsiteNamesToResult(); 

    return $this; 
} 

感謝,

回答

1

使用此代碼片段:

<?php 
    ini_set('display_errors', 1); 
    error_reporting(E_ALL); 
    require_once("app/Mage.php"); 
    Mage::app(); 

    $collection = Mage::getModel('catalog/product')->getCollection(); 
    $collection 
     ->joinField('category_id', 
      'catalog_category_product', 
      'category_id', 
      'product_id=entity_id', 
      null, 
      'right'); 

類別ID可以像訪問:

$product->getData('category_id'); 

因此將需要所有id在catalog_category_product表中的產品,換句話說,腳本將採用所有產品在類別中。

加載額外的屬性集合:

$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*'); 

更新1

我試着用你的 - 它完美的作品。

試一下這個 - 感謝您的答覆

$collection = $this->_prepareCollection(); 
$collection 
    ->joinField('category_id', 
     'catalog_category_product', 
     'category_id', 
     'product_id=entity_id', 
     null, 
     'right'); 
+0

傑克,捆綁。我想在產品網格上添加此過濾器。但是當我在網格集合代碼上應用您的代碼片段時,出現錯誤(重複的ID錯誤)。 :( – Adeel

+0

請在您的第一個消息代碼片段中加載您的收藏夾,我的代碼加載了所有具有任何類別的產品 –

+0

我編輯了這個問題,在這裏我想添加此檢查 – Adeel

相關問題