Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get product sku in Magento using product ID for big collections

Tags:

magento

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?

like image 605
PauGNU Avatar asked Dec 02 '22 21:12

PauGNU


2 Answers

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('*')

like image 135
ceckoslab Avatar answered Dec 23 '22 21:12

ceckoslab


To get separate attribute without loading product

$resource = Mage::getResourceSingleton('catalog/product');    
$sku = $resource->getAttributeRawValue($productId, 'sku', $storeId)
like image 44
Serhiy Gavrylov Avatar answered Dec 23 '22 21:12

Serhiy Gavrylov