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:
->s开发者_高级运维etPageSize(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.
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.
All collections are Varien_Data_Collection
objects so you can use getFirstItem
:
$modifiemoi = $mavaribale->getFirstItem();
精彩评论