Search code examples
magentosearchadvanced-search

Magento: Resource Model 'loadByAttribute' with multiple parameters


I need a way to locate a Magento object my multiple attributes. I can look up an object by a single parameter using the 'loadByAttribute' method, as follows.

$mageObj->loadByAttribute('name', 'Test Category');

However, I have been unable to get this to work for multiple parameters. For example, I would like to be able to do the above query using all of the following search parameters. It might look something like the following.

$mageObj->loadByAttribute(array('entity_id' => 128,
                                'parent_id' => 1,
                                'name' => 'Test Category'));

Yes, I know that you don't need all of these fields to find a single category record. However, I am writing a module to export and import a whole website, and I need to test if an object, such as a category, already exists on the target system before I create it. To do this, i have to check to see if an object of the same type, with multiple matching attributes already exists, even if it's ID is different.


Solution

  • This may not answer your question, but it may solve your problem.
    Magento does not support loadByAttribute for multiple attributes, but instead you can do this.

    $collection = $mageObj->getCollection()
        ->addAttributeToFilter('entity_id', 128)
        ->addAttributeToFilter('parent_id', 1)
        ->addAttributeToFilter('name', 'Test Category');
    $item = $collection->getFirstItem();
    if ($item->getId()){
        //the item exists
    }
    else {
        //the item does not exist
    }
    

    addAttributeToFilter works for EAV entities (products, categories, customers). For flat entities use addFieldToFilter.
    There is a special case for sales entities (orders, invoices, creditmemos and shipments) that can use both of them.