38

In the past to get all ID's of a product collection, I have always used getAllIds on the collection, believing this was a method that prevented the full collection load with data etc.

But, I actually looked at the method today and it loads the collection and iterates over each item to get the ID array.

public function getAllIds()
{
    $ids = array();
    foreach ($this->getItems() as $item) {
        $ids[] = $this->_getItemId($item);
    }
    return $ids;
}

My question is, what is the most efficient method to retrieve only the ID field from a collection?

3 Answers 3

46

Actually getAllIds is the best way of doing it. For example in the product collection resource model the method looks like this:

public function getAllIds($limit = null, $offset = null)
{
    $idsSelect = $this->_getClearSelect();
    $idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
    $idsSelect->limit($limit, $offset);
    $idsSelect->resetJoinLeft();

    return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
}

So everything is retrieved from a single select and no iteration is required. Also in the abstract resource model it looks like this:

public function getAllIds()
{
    $idsSelect = clone $this->getSelect();
    $idsSelect->reset(Zend_Db_Select::ORDER);
    $idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
    $idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
    $idsSelect->reset(Zend_Db_Select::COLUMNS);

    $idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
    return $this->getConnection()->fetchCol($idsSelect);
}

So everything that extends Mage_Core_Model_Resource_Db_Collection_Abstract should use this unless specified otherwise.

The method you looked at comes from the base class Varien_Data_Collection but it is overwritten in its children.

0
7

In this case you can use the collection object

$collection = Mage::getModel('catalog/product')->getCollection()
   ->addAttributeToSelect('entity_id');

[...] 
do your loop
[...]

addAttributeToSelect for entity_id is not really required but for demonstrating purposes I put it in, add the fields you need and you're done!

More on collections you'll find on this Wikipage

2

More Optimized

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->reset(Zend_Db_Select::COLUMNS);
$collection->getSelect()->columns('entity_id');
$collection1Ids[] = $collection->getAllIds();
1
  • This is also done by default ... see $this->_getClearSelect().
    – sv3n
    Feb 28, 2018 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.