4
votes

I have a catalog with near 90000 products. I need to retrieve all the products sku that have no image associated. With a sql query I can get the id list of all the products without image. From that ID I need to get the product sku. So, I have an $ids array with all the products without image (near 60000).

I'm trying to get all the corresponding skus by using something easy with the magento api:

foreach ($ids as $id){
   $product = Mage::getModel('catalog/product')->load($id);
   echo $product->getSku()."\n";
}

But this causes a PHP Fatal error: Allowed memory size... (memory size is 1024Mb and I cannot change it).

My question is: from this $ids array, how can I get all the corresponding sku without causing a memory size error? Is there a lighter way of getting a product attribute having the product id?

2

2 Answers

15
votes

Currently you are loading a lot of not needed product data and this causes a fatal error. In your case you need only product sku. I am suggestion to use Magento collections.

I guess, that the following code snippet will work for you:

$productsCollection = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('entity_id', array('in' => $ids));

foreach($productsCollection as $product) {
    echo $product->getSku();
}

Magento automatically adds the sku to the select, but pay attention, that sometimes you may want to get some custom product attribute, e.g. attribute with code "color". Then you need to add ->addAttributeToSelect('color') and the code will look like:

$productsCollection = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('entity_id', array('in' => $ids))
                    ->addAttributeToSelect('color');

foreach($productsCollection as $product) {
    echo $product->getSku();
    echo $product->getColor();
}

If you want to get all product attributes you can use ->addAttributeToSelect('*')

3
votes

To get separate attribute without loading product

$resource = Mage::getResourceSingleton('catalog/product');    
$sku = $resource->getAttributeRawValue($productId, 'sku', $storeId)