2016-01-21 24 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

相关问题