0

I need a script that will check all magento products and set them to instock if the qty is greater than 0.

The plan is to run this as a scheduled cronjob so that it will be checking for any products that have their stock value incorrectly set.

My code is rather crude so far but here is what i have come up with:

<?php PHP_SAPI == 'cli' or die;
ini_set('memory_limit','1024M');
set_time_limit(0);
error_reporting(E_ALL | E_STRICT);
require_once '../app/Mage.php';
umask(0);
Mage::app();

$product = Mage::getModel('catalog/product')->load($product_id);
$stock_item = $product->getStockItem();

     if ($stock_item->getQty() < 0){
        $stockItem->setIsInStock(true);
        $stockItem->save();
        $product->save();
     }
?>

Unfortunately when i run this nothing changes in the backend and no products are set to instock as they should.

Perhaps somebody could point to where i'm going wrong or a better solution?

1
  • if ($stock_item->getQty() > 0) and check the manage_stock to 1. – Albeis Aug 6 '18 at 13:07
0

Also, you can try this way. Hope it works.

$_product = Mage::getModel ( 'catalog/product' )->load($product_id);
$stockItem =    Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product->getId());
        if($stockItem->getQty() > 0) {
           $stockItem->setData('is_in_stock', 1);
           $stockItem->setData('manage_stock', 1);                  
        } else {
           $stockItem->setData('is_in_stock', 0);
                        }
        $stockItem->save();
1
  • Thanks @albeis i've tried your code above but for some reason i'm getting integrity contstraint errors now. [06-Aug-2018 16:54:02 UTC] PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (willowhill_ma156.mgax_cataloginventory_stock_item, CONSTRAINT FK_MGAX_CATINV_STOCK_ITEM_PRD_ID_MGAX_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (product_id) REFERENCES mgax_catalog_product_entit) in /home/willowhill/public_html/lib/Zend/Db/Statement/Pdo.php:228. – markbarabus Aug 6 '18 at 17:02

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.