Magento验证产品是否存在
There is a way to validate if the product exist or if it was created by product id
for example
$_prodId = $this->getProduct()->getId();
if (function_exists($_prodId)){
Thanks
有一种方法可以验证产品是否存在或是否是按产品ID创建的 p>
例如 p>
$ _ prodId = $ this-> getProduct() - > getId();
if(function_exists($ _ prodId) ){
code> pre>
谢谢 p>
div>
You can validate as follows.
$_prodId = $this->getProduct()->getId();
$_product = Mage::getModel('catalog/product')->load($_prodId);
if($_product)
{
//product exists
}
else
{
//product doesn't exist
}
The other answer posted is very tough on resources, a better way to do this is a simple query to the DB, you can do this with
$sku = Mage::getResourceSingleton('catalog/product')->getProductsSku(array($_prodId));
if(!empty($sku)){
//do your thang
}
This function is meant to be used to obtain the sku when you have the ID, but we can use it here, if the product does not exist it will return an empty array:
array(0) {
}
If it DOES exits it will return an array with the id and the sku
array(1) {
[0]=>
array(2) {
["entity_id"]=>
string(6) "185566"
["sku"]=>
string(9) "ID-136308"
}
}
We can even use it to do multiple products at the same time or whatever.
If we look at the method's definition on the core
public function getProductsSku(array $productIds)
{
$select = $this->_getReadAdapter()->select()
->from($this->getTable('catalog/product'), array('entity_id', 'sku'))
->where('entity_id IN (?)', $productIds);
return $this->_getReadAdapter()->fetchAll($select);
}
Very simple and far more lightweight than loading the product's model
you can use this code to check Product Sku is present or not.
Include this class in your constructor.
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder;
\Magento\Catalog\Model\ProductRepository $_productRepository
Add this below logic where you need the condition.
$productSku = "*Your_Product_Sku*";
$searchCriteria = $this->searchCriteriaBuilder->addFilter("sku", $productSku,'eq')->create();
$products = $this->_productRepository->getList($searchCriteria);
$Items = $products->getItems();
if (count($Items) == 0) {
//your message here.
}