Magento – Get Product Collection Without Sub-Products of Configurable Products

collection;configurable-productmodelproduct-collection

I want to get a list of all products available in my Magento installation. Currently I am using the following call to filter out enabled products and limit the result set to those products which are visible both in catalog and search results:

$products = \Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('status', \Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
    ->addAttributeToFilter('visibility', array('in' => array(
        \Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH,
        \Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
    )))
    ;

As all children of configurable products are stored as regular products they show up in the resulting collection. However, I don't want them to be included. Is there any way to safely achieve this?

In case you wonder about all these backslashes: My code runs in an PHP-5.3 compatible environment using namespaces so I had to refer to the global namespace when calling Magento functions.

Thanks in advance,

Edit (further explanation of what I want to achieve):

My employer develops an own eCommerce system. This software provides a mechanism similar to Magento's configurable products. All sub-products assigned to a configurable product know about their parent (indicated by the parent's primary key). Hence, it it easy to filter them out by excluding product rows having a non-zero parent ID.

How is this realized in Magento? Don't the sub products know which configurable product they are assigned to?

Best Answer

Figured it out by myself. The table catalog_product_relation contains information about parent-child relationships for configurable products. I just had to join the table to my collection and look for product records that do not have a corresponding row in catalog_product_relation with their entity_id as child_id. Quite simple if you know what you have to do.

    $products = Mage::getResourceModel('catalog/product_collection')
        ->joinTable('catalog/product_relation', 'child_id=entity_id', array(
            'parent_id' => 'parent_id'
        ), null, 'left')
        ->addAttributeToFilter(array(
            array(
                'attribute' => 'parent_id',
                'null' => null
            )
        ));