Check If Product Exists

2020-06-30 03:32发布

问题:

I have some php code which I use SKU for it:

$sku = $id
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds(); 

What I would like to add to this code if $sku is wrong (Not found in database with $_product line) to be able to change it manually for example if the $sku is not existent change it to $sku = "909010";

Thank you for the help

回答1:

function get_product($sku){

$product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); 
    if (!$product){
        $new_sku = '909010'; // If Real SKU doesn`t exsist, change to '909010'
        $product=Mage::getModel('catalog/product')->loadByAttribute('sku',$new_sku);
    }
    return $product;        
}

var_dump(get_product('your-sku')); // Real Sku 


回答2:

$sku = $id
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
if(!is_object($_product) || !$_product->getId()){
    //do your stuff here
}
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds(); 


回答3:

$sku = $id
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)

$_product = !empty($product) ? $product : Mage::getModel('catalog/product')->loadByAttribute('sku','YOUR-ERROR-SKU');

$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds(); 


标签: magento