Magento – Magento – custom (non eav) model, load by multiple fields

collection;model

I have a custom model and resource model. I want to load a single instance of the model using more than 1 field.

The model has the following fields:

id
tag_name
custom_name
group_name

I want to load this model based on on tag_name, custom_name and group_name instead of id.

Currently i am using a collection and addFilter for each field. This works, but i wondered if there is a standard strategy for this type of thing in Magento?

EDIT

Core magento seems not to use collections for this scenario but instead it uses direct sql queries in the resource models.

an example of this is:

loadByAccountAndDate() in Mage_Paypal_Model_Resource_Report_Settlement

Is there a reason for this, when collections seem to be a more concise way, in terms of amount of code to be written

I just dont know why magento chooses to do it this way

Best Answer

I think this is a good approach. Maybe you need to create a wrapper in the model class so you will avoid writing the same thing over and over again.
Something like:

public function loadByMultiple($tag, $customName, $group){
    $collection = $this->getCollection()
            ->addFieldToFilter('tag_name', $tag)
            ->addFieldToFilter('custom_name', $customName)
            ->addFieldToFilter('group_name', $group);
    return $collection->getFirstItem();
}

And you can load the item like this in any other place:

$model = Mage::getModel('model/class_here')->loadByMultiple($tag, $customName, $group);
if ($model->getId()){
   //the instance exists
}
else{
    //not found
}