Magento Collection – Determine if Attribute is in Select

attributescollection;event-observerjoin;product-collection

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.

Best Answer

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.