0

Are there side-effects, or issues with doing something like this:

// Retrieve the Model once
$model = Mage::getModel('some/model';

// Load several different instances
foreach($idlist as $id)
{
    $entity = $model->load($id);
}

Or should the Model be retrieved within the loop?

// Load several different instances
foreach($idlist as $id)
{
    // Retrieve the Model once per instance
    $model = Mage::getModel('some/model';
    $entity = $model->load($id);
}
STW
  • 2,047
  • 3
  • 16
  • 41

2 Answers2

1

Yes there are side effects to using the same model instance for loading more than one instance.
When calling load on a model, the data from the model is merged with the values from the database.
So in case the second instance has a field set to null in the database there is a chance that it won't be null if it had a different value in the previous instance.

Use the second approach if you have to. But using load in a loop is not recommended.

Here is what can happen if you use the same model instance for multiple load statements: Product loop giving incorrect images

Marius
  • 197,939
  • 53
  • 422
  • 830
0

Any model load is very consuming. Your second solution is a tad better but still not great. Most of people use "load()" because it's the easiest way to get all the data from a model. Although the best solution is to actually add this data to the collection and only select what you need.

Fran Mayers
  • 2,803
  • 9
  • 12
  • I assume you're referring to something like Mage::getModel('some/model')->getCollection()->addAttributeToFilter('entity_id' -> array('in', array(1,2,3))?

    We usually do it that way, this question was specific to one to many vs one to one getModel():load() calls--so a foreach better demonstrated it.

    – STW Jun 26 '14 at 19:47
  • What I am trying to say is that you shouldn't even load the model, it's going to be greedy regardless of the solution you go for. – Fran Mayers Jun 26 '14 at 21:33