简体   繁体   English

Magento测试是否存在产品集合

[英]Magento test if a collection of products exist

public function getAllProductById($id=0)
{
    $products = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('entity_id', array('eq' => $id))
        ->joinTable(
            'cataloginventory_stock_item',
            'product_id=entity_id',
            array('quantite' => 'qty'),
            null,
            'left'
        )
        ->load()
    ;

    if ($products) {
        return $products;
    } else {
        return $products == null;
    }
}

The variable $products doesn't return null even when I use an id ($id) which is not set in Magento. 即使我使用未在Magento中设置的id($ id),变量$products也不返回null。

Replace your code 替换您的代码

if ($products) {
        return $products;
    } else {
        return $products == null;
    }

with

if ($products->count()) {
        return $products;
    } else {
        return $products = null;
    }

Just replace $products with $products->count() . 只需将$products替换$products $products->count() This will give you zero if there is no product in your collection. 如果您的收藏中没有产品,这将为您提供零。 Like this below: 如下所示:

if ($products->count()) {
    return $products;
} else {
    return $products = null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM