获取具有产品的属性的样本数

Get number of swatches of an attribute that has a product

我有带有样本属性的可配置产品,在本例中是颜色。

我需要知道一个产品有多少种颜色(数量),或者可能有多少个单一产品组成了这个可配置的产品。

事实上,我需要知道产品中何时有不止一种颜色。

终于找到了,也许对以后的人有帮助:

$productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

//in this case the attribute color that I needed is in [0] position
$available_colors = sizeof($productAttributeOptions[0]["values"]);

if ($available_colors >1):
    //custom code
endif;

编辑: 此解决方案适用于一种产品,或至少适用于几种产品,但如果您需要在产品列表中使用它,运行 每个产品中都有此代码。有时它会超时并关闭数据库连接,因此网络会因错误而崩溃。

终于找到了一个解决方案,也许不是最好的,但与我之前使用的相比,它是相当快的:

$_idsForTheQuery = $_productCollection->getAllIds();

    $read = Mage::getSingleton('core/resource')->getConnection('core_read');
    $sql_query = "SELECT parent_id, COUNT(parent_id) AS colors FROM
                (SELECT cpr.parent_id FROM `eav_attribute` a
                LEFT JOIN `catalog_product_entity_int` cpei ON cpei.attribute_id=a.attribute_id
                LEFT JOIN `catalog_product_relation` cpr ON cpr.child_id=cpei.entity_id
                WHERE attribute_code = 'color' AND cpr.parent_id IN (".implode (", ", $_idsForTheQuery).") 
                GROUP BY cpr.parent_id, cpei.value) colors 
                GROUP BY parent_id";

    $results = $read->query($sql_query);

    $number_of_colors_by_id_array = array();
    foreach($results as $r)
    {
        $number_of_colors_by_id_array[$r["parent_id"]] = $r["colors"];
    }

然后在产品的 foreach 循环中

<?php if ($number_of_colors_by_id_array[$_product->getId()]>1): ?>
    <div class="aditional-colors-message">
        <?php echo __('more colors available'); ?>        
    </div>
<?php endif; ?>