Magento getAttributeText() not working in shell sc

2019-08-05 10:21发布

问题:

I have the following code to loop over all products and echo the sku and manufacturer, but $manu is always blank, even though I do get the sku correctly.

private function organize() {
    $products = Mage::getModel('catalog/product')->getCollection();
    foreach ($products as $product) {
        $sku = $product->getSku();
        $manu = $product->getAttributeText('manufacturer');
        // The following also doesn't work
        //$manu = $product->getResource()->getAttribute('manufacturer')->getFrontend()->getValue($product);
        echo $sku." - ".$manu."\n";
    }
}

This is running as a command line script extending from Mage_Shell_Abstract

What could be wrong with my code?

David

回答1:

I prefer @Tim 's comment (of course credit for him) as we don't need to do another load of product (it is automatically loaded when we do foreach from our collection)

The manufacturer attribute is not automatically selected as it is not stored in the main table (catalog_product_entity).

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('manufacturer');


回答2:

When iterating through the collection here, EAV attributes are not loaded. Try this instead:

$products = Mage::getModel('catalog/product')->getCollection();
    foreach ($products->getAllIds() as $productId) {
        $product = Mage::getModel('catalog/product');
        $product->load($productId);
        $sku = $product->getSku();
        $manu = $product->getAttributeText('manufacturer');
        echo $sku." - ".$manu."\n";
    }


标签: magento