2016-01-21 25 views
0

我正在創建magento API,因此我需要從類別ID和目錄屬性標識中獲取產品集合。獲取Magento中的產品集合,按類別和自定義屬性值進行過濾

對於例如: 我有類名稱測試和id是1。此外,我已設置屬性color(從catalog->attributes->manage attributes),並且我已爲此顏色屬性設置了值,如white,blue,black

現在我添加了幾個產品,它的類別是測試(id = 1)和顏色屬性設置white

我的問題是: 現在我想要獲得產品系列,其ID爲1,顏色爲white

我怎樣才能得到這個集合。 在此先感謝

回答

4
<?php 
// load category object by category ID 
$category = Mage::getModel('catalog/category')->load(1); 

// get product collection, filter it by category, 
// add the color attribute to select to be able to filter using it later 
$productCollection = Mage::getResourceModel('catalog/product_collection') 
         ->addCategoryFilter($category) 
         ->addAttributeToSelect('color') 
         ->addFieldToFilter(array(
          array('attribute'=>'color','eq'=>'white'), 
         )); 

更多信息檢查

How to get products from a particular category in magento ecommerce

Magento - Retrieve products with a specific attribute value

https://magento.stackexchange.com/questions/5838/get-product-collection-from-a-category-id

+0

如果我想用顏色和大小來篩選,然後 - > addAttributeToSelect(陣列('顏色','尺寸')工作與否?如果不是,那麼通過顏色和尺寸進行收集的正確方法是什麼。 – Dhaval

+0

我不是100%確定這是否可行,但據我所知並嘗試過自己,addAttributeToSelect()用於將屬性添加到查詢的select部分,這允許您稍後進行過濾使用它。 –

+0

以非常簡單的方式(表/列名不是真),假設這是原始查詢'SELECT id,sku FROM products',但我們要使用屬性'color'和值'white'進行過濾,所以我們必須告訴Magento將顏色屬性添加到查詢中,該查詢將其更改爲「SELECT id,sku,color FROM products」,然後我們要告訴Magento爲「color」過濾特定值,這會更改查詢到'SELECT ID,sku,顏色從產品WHERE顏色='white'' –

0
<?php 
    $attributeCode = 'Your_Attribute_Code'; 
    $attributeOption = 'Attribute_Option'; 
    $attributeDetails = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode); 
    $options = $attributeDetails->getSource()->getAllOptions(false); 
    $selectedOptionId = false; 

    foreach ($options as $option){ 
     if ($option['label'] == $attributeOption) { 
      $selectedOptionId = $option['value']; 
     } 
    } 

    if ($selectedOptionId) { 
     $products = Mage::getModel('catalog/product') 
      ->getCollection() 
      ->addAttributeToSelect('*') 
      ->addAttributeToFilter($attributeCode, array('eq' => $selectedOptionId)); 

     foreach($products as $product){ 
      echo $product->getId(); 
      echo $product->getName(); 
     } 
    } 
?> 
+0

請詳細說明爲什麼這個解決方案的工作,謝謝! – Alex

相關問題