Llian
Llian

Reputation: 362

What is the best way to check if a product id is valid in magento?

For a backend module I have the need to check if a product id is valid, that is: is there a product with that id? I've found two solutions for that, but I'm not very happy with either one:

  1. Directy query the catalog_product_entity table. Very fast but definitely not very elegant and I fear there might be issues I'm not aware of.

  2. Use the following code:

    $product = Mage::getModel('catalog/product')->load($productID)
    if ($product->getId()) {
      //valid id
    }
    else {
      //not a valid id
    }
    

    This should work but it's painfully slow, because I have to check several IDs at once. And since I don't need the actual product data, it doesn't really make sense to load it.

Any better suggestions?

Upvotes: 1

Views: 4058

Answers (4)

benmarks
benmarks

Reputation: 23205

$productIds = array(16,17,18,19,290993,25    /*...*/);

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addFieldToFilter('entity_id',array('in'=>$productIds))->load();

$foundIds = array_intersect($productIds,array_keys($collection->toArray()));

var_dump($foundIds); /* each array value should be a valid ID */

Upvotes: 5

james
james

Reputation: 792

Try this:

$collection->getAllIds();

You'll get an array of all the product IDs, and you can then do an in_array to check for validity. Take a look at

Mage_Catalog_Model_Resource_Product_Collection

to see how it's done.

EDIT

Example:

function isProductIdValid($productId)
{
    // Allows model overrides (other modules) to work correctly.
    // Returns all valid IDs
    $collection  = Mage::getModel('catalog/product')->getCollection();
    $productIds = $collection->getAllIds();

    if (in_array($productId, $productIds)) {
        return true;
    } else {
        return false;
    }
}

Upvotes: 3

Llian
Llian

Reputation: 362

Thanks benmarks and james, you've pointed me in the right direction and I just combined your approches:

$productIds = array(16,17,18,19,290993,25    /*...*/);

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addFieldToFilter('entity_id',array('in'=>$productIds));

$foundIds = $collection->getAllIds();

var_dump($foundIds); /* each array value should be a valid ID */

For some reason, getAllIds() returns Ids as strings rather than ints, but that's fine.

Upvotes: 3

Lucas Moeskops
Lucas Moeskops

Reputation: 5443

For having it fast, raw queries seem definitely the fastest to me always :-)

But maybe preload all id's like this could help?

$collection = Mage::getModel('catalog/product')->getCollection()->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns(array('entity_id'));

$ids = array();
foreach ($collection as $product) {
  $ids[] = $product->getId();
}

Then you can just test with the in_array method if an id exists.

Upvotes: 0

Related Questions