0

I'm doing some customization on magento 1.9.x website. I need to get all products with in stock and manage stock enabled

I'm using this code

$stockCollection = Mage::getModel('cataloginventory/stock_item')
        ->getCollection()
        ->addFieldToFilter('is_in_stock', 1);

    $productIds = array();

    foreach ($stockCollection as $item) {
        $productIds[] = $item->getOrigData('product_id');
    }

    $productCollection = Mage::getModel('catalog/product')->getCollection()
->addFieldToFilter('entity_id', array('in'=> $productIds));
    $productCollection->load();


    $i=0;
    foreach ($productCollection as $_product) {
        $i++;
        echo $i.'-'.$_product->getId().'<br/>';
    }

But the problem is this list shows the items which not enable manage stock like this

enter image description here

I only need to get products which manage stock enabled and in stock

like below

enter image description here

Anyone know how to get that with my code or using another code, Thank You

1

Just add the manage inventory column to the collection, try this:

$stockCollection = Mage::getModel('cataloginventory/stock_item')
        ->getCollection()
        ->addFieldToFilter('is_in_stock', 1)
        ->addFieldToFilter('manage_stock', 1)

$productIds = []];

foreach ($stockCollection as $item) {
    $productIds[] = $item->getOrigData('product_id');
}

$productCollection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addFieldToFilter('entity_id', ['in'=> $productIds])
    ->load();


$i=0;

foreach ($productCollection as $_product) {
    $i++;
    echo $i.'-'.$_product->getId().'<br/>';
}
1

You can add an OR condition in the code inorder to check the use_config_manage_stock

$stockCollection = Mage::getModel('cataloginventory/stock_item')
        ->getCollection()
        ->addFieldToFilter('is_in_stock', 1)
        ->addFieldToFilter(
    array('manage_stock', 'use_config_manage_stock'),
    array(
        array('eq'=>'1'), 
        array('eq'=>'1')
    )
);

$productIds = [];

foreach ($stockCollection as $item) {
    $productIds[] = $item->getProductId();
}

$productCollection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addFieldToFilter('entity_id', ['in'=> $productIds])
    ->load();

$i = 0;
foreach ($productCollection as $_product) {
    $i++;
    echo $i.'-'.$_product->getId().'<br/>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.