Tuesday, February 24, 2015

Get product information with stock quantity

Solution 1:

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo 'Must be called from the command line.';
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1_us/app/Mage.php';

#Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

getProductInfoArr();

function getProductInfoArr($optArr = array()) {
  $outArr = array();

  $collection = Mage::getModel('catalog/product')
    ->getCollection()
    #->addAttributeToSelect('*')
    ->addAttributeToSelect(array('id', 'sku'))
    ->joinTable(
      array('s' => 'cataloginventory/stock_item'),
      'product_id = entity_id',
      array('qty' => 'qty'), // array('field_name_alias' => 'field_name') // Make sure you do use lower case for the alias.
      '{{table}}.stock_id = 1',
      'inner'
    )
    ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
    ->load();

  #echo '<pre>' . $collection->getSelect()->__toString() . '</pre>';

  foreach ($collection as $prodObj) {
    #echo '<pre>' . print_r($prodObj->debug(), TRUE) . '</pre>';

    $outArr[$prodObj->getSku()] = array(
      'itemId' => $prodObj->getId(),
      'itemQty' => (int) $prodObj->getQty(),
    );
  }

  return $outArr;
}
?>

Solution 2:

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo 'Must be called from the command line.';
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1_us/app/Mage.php';

#Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

getProductInfoArr();

function getProductInfoArr($optArr = array()) {
  $outArr = array();

  $collection = Mage::getModel('catalog/product')
    ->getCollection()
    #->addAttributeToSelect('*')
    ->addAttributeToSelect(array('id', 'sku'))
    ->joinField(
      'qty',
      'cataloginventory/stock_item',
      'qty',
      'product_id = entity_id',
      '{{table}}.stock_id = 1',
      'inner'
    )
    ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
    ->load();

  #echo '<pre>' . $collection->getSelect()->__toString() . '</pre>';

  foreach ($collection as $prodObj) {
    #echo '<pre>' . print_r($prodObj->debug(), TRUE) . '</pre>';

    $outArr[$prodObj->getSku()] = array(
      'itemId' => $prodObj->getId(),
      'itemQty' => (int) $prodObj->getQty(),
    );
  }

  return $outArr;
}
?>

No comments: