Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a single entity from a magento model collection

I'm encountering an issue because I'm sure I'm not doing this correctly with my programming. I have created a custom model in Magento.
In the database table of my model there are several entities with the same attributes...

I need to pick just one from all these entities with the same attribute that I have. For the moment I did this:

$myvariable = Mage::getModel('test/test')->getCollection()
->setOrder('idserialkeys', 'asc')
->addFilter('idproduit', 1)
->addFilter('utilise', 0)
->addFilter('customerid', 0)
->addFilter('numcommande', 0)

From this loading I have around a hundred results but I need to update only one of these, so just after I'm doing:

->setPageSize(1);

The problem is that I need a foreach after to update my entity

foreach($mavaribale as $modifiemoi) {
    // Update of my entity because of course there is only one 
}

As you can see I'm obliged to do a loop (for each) even if I have a setPagesize... I would like to avoid this loop to optimize my code.

like image 689
Anselme Avatar asked Mar 21 '11 14:03

Anselme


2 Answers

When you have a collection, and you only need one element, use the getFirstItem method. Try this:

$modifiemoi = $myvariable->getFirstItem();

Make sure that you also use your setPageSize call so that you only transfer data for one item.

like image 63
Joe Mastey Avatar answered Oct 25 '22 16:10

Joe Mastey


All collections are Varien_Data_Collection objects so you can use getFirstItem:

$modifiemoi = $mavaribale->getFirstItem();
like image 41
clockworkgeek Avatar answered Oct 25 '22 17:10

clockworkgeek