如何在Magento中获取产品集合的所有属性(在前端可见)及其相应选项?

如何在Magento中获取产品集合的所有属性(在前端可见)及其相应选项?,magento,Magento,比如说,这些是颜色和大小的属性。颜色有以下选项红色、绿色和蓝色,尺寸有以下选项小、中、大。现在,假设product collection中有两个产品,一个产品为红色,尺寸较小,另一个产品为绿色,尺寸中等。所以,我希望输出如下 颜色:红色、绿色 尺寸:小型、中型 我不想先获取属性列表集合,然后迭代并匹配集合中每个产品的属性,因为这将非常缓慢且占用内存。我调试了Magento中分层导航的工作方式,并基于此提出了下面提到的解决方案 try{ //Get product collec

比如说,这些是颜色和大小的属性。颜色有以下选项红色、绿色和蓝色,尺寸有以下选项小、中、大。现在,假设product collection中有两个产品,一个产品为红色,尺寸较小,另一个产品为绿色,尺寸中等。所以,我希望输出如下

  • 颜色:红色、绿色
  • 尺寸:小型、中型

我不想先获取属性列表集合,然后迭代并匹配集合中每个产品的属性,因为这将非常缓慢且占用内存。

我调试了Magento中分层导航的工作方式,并基于此提出了下面提到的解决方案

try{
        //Get product collection and apply filter to it if any. Here I am applying dummy color filter
        $prodCollection = Mage::getModel('catalog/product')->getCollection()
                        ->addAttributeToFilter('color',array('in' => array(3,4))); //change this filter ad per your need

        $prodCollection
            ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
            ->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addUrlRewrite(Mage::getModel('catalog/layer')->getCurrentCategory()->getId());

        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($prodCollection);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($prodCollection); 

        $setId = 4; //default attribute set id. change this as pre your need. You can also make this an array

        //Get catalog attribute collection of some attribute sets.
        $attrCollection = Mage::getResourceModel('catalog/product_attribute_collection');
        $attrCollection
            ->setItemObjectClass('catalog/resource_eav_attribute')
            ->setAttributeSetFilter($setId)
            ->addStoreLabel(Mage::app()->getStore()->getId())
            ->setOrder('position', 'ASC');

        $attrCollection->addIsFilterableFilter(); //Check if attributes are filterable or not

        $attrCollection->load();

        $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
        $filterResourceModel = Mage::getResourceModel('catalog/layer_filter_attribute');

        //Apply filter to product collection, if any
        if(1){ //Check if any filters are applied on product collection from query string (?color=4&size=8)
            foreach($attrCollection as $attribute){

                //For now just for testing purpose, I have hardcoded it to work only for single attribute i.e. color
                if($attribute->getAttributeCode() != 'color'){
                    continue;
                }

                //I am assuming color filter is applied twice 
                $filterName = 'color';
                $filterId = 92;
                $filterVal = array(3,4);      

                $tableAlias = $attribute->getAttributeCode() . '_fa';

                $conditions = array(
                    "{$tableAlias}.entity_id = e.entity_id",
                    $connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
                    $connection->quoteInto("{$tableAlias}.store_id = ?", $prodCollection->getStoreId()),
                    $connection->quoteInto("{$tableAlias}.value IN (?)", $filterVal)
                );

                $prodCollection->getSelect()->join(
                    array($tableAlias => $filterResourceModel->getMainTable()),
                    implode(' AND ', $conditions),
                    array()
                );

            }
        }


        //Iterate each attribute one by one. For now just for testing purpose, I have hardcoded it to work only for single attribute i.e. color
        foreach($attrCollection as $attribute){
            if($attribute->getAttributeCode() != 'color'){
                continue;
            }

            //find attributes options
            $options = $attribute->getFrontend()->getSelectOptions();

            // clone select from collection with filters
            $select = clone $prodCollection->getSelect();
            // reset columns, order and limitation conditions
            $select->reset(Zend_Db_Select::COLUMNS);
            $select->reset(Zend_Db_Select::ORDER);
            $select->reset(Zend_Db_Select::LIMIT_COUNT);
            $select->reset(Zend_Db_Select::LIMIT_OFFSET);

            $tableAlias = sprintf('%s_idx', $attribute->getAttributeCode());
            $conditions = array(
                "{$tableAlias}.entity_id = e.entity_id",
                $connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
                $connection->quoteInto("{$tableAlias}.store_id = ?", Mage::app()->getStore()->getId()),  //$filter->getStoreId()
            );

            $select
                ->join(
                    array($tableAlias => $filterResourceModel->getMainTable()),
                    join(' AND ', $conditions),
                    array('value', 'count' => new Zend_Db_Expr("COUNT({$tableAlias}.entity_id)")))
                ->group("{$tableAlias}.value");


            $optionsCount = $connection->fetchPairs($select);


            $data = array();
            foreach ($options as $option) {
                if (is_array($option['value'])) {
                    continue;
                }
                if (Mage::helper('core/string')->strlen($option['value'])) {
                    $data[] = array(
                            'label' => $option['label'],
                            'value' => $option['value'],
                            'count' => isset($optionsCount[$option['value']]) ? $optionsCount[$option['value']] : 0,
                        );
                }

            }  
            echo '<pre>'; print_r($data); die('<><>');
          }        
    }catch(Exception $e){

    }
试试看{
//获取产品集合并对其应用过滤器(如果有)。这里我应用虚拟颜色过滤器
$prodCollection=Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('color',array('in'=>array(3,4));//根据需要更改此筛选器广告
$prodCollection
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes()
->AddPrice()
->addFinalPrice()
->addTaxPercents()
->addUrlRewrite(Mage::getModel('catalog/layer')->getCurrentCategory()->getId());
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($prodCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($prodCollection);
$setId=4;//默认属性集合id。根据需要更改它。您也可以将其设置为数组
//获取某些属性集的目录属性集合。
$attrCollection=Mage::getResourceModel('catalog/product_attribute_collection');
$attrCollection
->setItemObjectClass('目录/资源\u eav\u属性')
->setAttributeSetFilter($setId)
->addStoreLabel(Mage::app()->getStore()->getId())
->设置顺序(“位置”、“ASC”);
$attrCollection->addIsFilterableFilter();//检查属性是否可过滤
$attrCollection->load();
$connection=Mage::getSingleton('core/resource')->getConnection('core_read');
$filterResourceModel=Mage::getResourceModel('catalog/layer_filter_attribute');
//将筛选器应用于产品集合(如果有)
if(1){//检查是否对查询字符串中的产品集合应用了任何筛选器(?color=4&size=8)
foreach($attrCollection作为$attribute){
//现在只是为了测试的目的,我已经硬编码它只适用于单一属性,即颜色
如果($attribute->getAttributeCode()!='color'){
继续;
}
//我假设颜色过滤器应用了两次
$filterName='color';
$filterId=92;
$filterVal=数组(3,4);
$tableAlias=$attribute->getAttributeCode();
$conditions=数组(
“{$tableAlias}.entity\u id=e.entity\u id”,
$connection->quoteInto(“{$tableAlias}.attribute_id=?”,$attribute->getAttributeId()),
$connection->quoteInto(“{$tableAlias}.store_id=?”,$prodCollection->getStoreId()),
$connection->quoteInto((?),$filterVal中的“{$tableAlias}.value”)
);
$prodCollection->getSelect()->join(
数组($tableAlias=>$filterResourceModel->getMainTable()),
内爆('和',$条件),
数组()
);
}
}
//一个接一个地迭代每个属性。目前,仅出于测试目的,我已经硬编码它,使其仅适用于单个属性,即颜色
foreach($attrCollection作为$attribute){
如果($attribute->getAttributeCode()!='color'){
继续;
}
//查找属性选项
$options=$attribute->getFrontend()->getSelectOptions();
//使用筛选器从集合中克隆选择
$select=clone$prodCollection->getSelect();
//重置列、顺序和限制条件
$select->reset(Zend_Db_select::COLUMNS);
$select->reset(Zend_Db_select::ORDER);
$select->reset(Zend\u Db\u select::LIMIT\u COUNT);
$select->reset(Zend\u Db\u select::LIMIT\u OFFSET);
$tableAlias=sprintf('%s_idx',$attribute->getAttributeCode());
$conditions=数组(
“{$tableAlias}.entity\u id=e.entity\u id”,
$connection->quoteInto(“{$tableAlias}.attribute_id=?”,$attribute->getAttributeId()),
$connection->quoteInto(“{$tableAlias}.store_id=?”,Mage::app()->getStore()->getId()),//$filter->getStoreId()
);
$select
->加入(
数组($tableAlias=>$filterResourceModel->getMainTable()),
联接('和',$条件),
数组('value','count'=>new Zend_Db_Expr(“count({$tableAlias}.entity_id)”))
->组(“{$tableAlias}.value”);
$optionsCount=$connection->fetchPairs($select);
$data=array();
foreach($options作为$option){
if(是_数组($option['value'])){
继续;
}
if(Mage::helper('core/string')->strlen($option['value'])){
$data[]=数组(
'label'=>$option['label'],
'value'=>$option['value'],
'count'=>isset($optionsCount[$option['value']])?$optionsCount[$option['value']]:0,