1

I want to join a custom field to a product collection, and the field I'm using to join it on is a custom attribute.

My observer method is currently doing this:

# Event: global/catalog_product_collection_load_before
public function addColourName(Varien_Event_Observer $observer)
{
    $collection = $observer->getEvent()->getCollection();

    $collection->joinTable(
        'colours/product_colour',              // my custom model
        'colour_code = existing_colour_code',  // my custom attribute on the product
        ['colour_name'],                       // the joined field I want  
        null,
        'left'
    );

    return $this;
}

So I want to join my colours/product_colour model on the product's existing attribute existing_colour_code = product_colour.colour_code, so I can retrieve the colour_name from that model.

All works correctly if I do the following:

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*');

foreach ($products...

However if I haven't added existing_colour_code to the select, then my observer will fail since the attribute doesn't exist to use in the join.

Question: Is there a way I can check to see if existing_colour_code has been added to the select so I can prevent this happening? Obviously I don't want to add it to the select for all product collections, simply ignore the joined field if it isn't required.

I was hoping for something along the lines of getAttributeInSelect($attrName), to match addAttributeToSelect() and removeAttributeToSelect(), but I can't see anything obvious, and the array containing the select attributes is protected so I can't access it from an observer.

1 Answer 1

2

To me the only way to know is by using the select statement directly:

$collection->getSelect()->getPart('columns');

This code should give you the list of columns to be selected.

2
  • I feel like that is acceptable if done from within a resource model. What do you think?
    – scrowler
    Commented May 23, 2016 at 8:04
  • @RobbieAverill well yeah in an ideal world, every CRUD operations should be done via resource models. But in that case, this code does not read the DB, it only uses the collection select to check the columns to be selected by the SQL query that will be run by the resource models. Commented May 23, 2016 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.