Get product collection in Magento, filtered by Cat

2019-09-07 15:49发布

问题:

I am creating magento API so now I need to get product collection from category id and catalog attribute id.

for ex : I have category with name test and id is 1 . Also I have set attribute color (from catalog->attributes->manage attributes) and I have set values for this color attribute like white , blue , black.

now I add few product and it's category is test (id=1) and color attribute is set white.

My Question is : Now I want to get product collection for whom category id is 1 and color is white.

How can I get this collection. Thanks in advance

回答1:

<?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'),
                       ));

More info check

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



回答2:

<?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();
        }
    }
?>


标签: magento