Pergunta

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

Foi útil?

Solução

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/>';
}

Outras dicas

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/>';
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top