Best seller code not showing simple children of configurables
Question
I am using the code below (similar all over the web) to retrieve bestsellers by sku. However it on works on simple products (that are visible) and on simple products (not visible/child products) that are ordered directly by sku, using either EE 1.12 'Order By Sku' or by ordering the child sku directly from the Admin.
It is not showing the same exact sku on the same order when it is ordered as a size of a configurable product.
Am I missing something? Correct store, doesn't seem visibility matters.
$_product = Mage::getResourceModel('reports/product_sold_collection')
->addAttributeToSelect('*')
->addOrderedQty()
->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();
Solution
If you look at the select that is used when building this query you can see that when joining to the catalog_product_entity
table it filters so that it only joins to simple products.
/** @var Mage_Reports_Model_Resource_Product_Sold_Collection $report */
$report = Mage::getResourceModel('reports/product_sold_collection')
->addAttributeToSelect('*')
->addOrderedQty();
mage::log((string) $report->getSelect());
This will show you the following sql.
SELECT
SUM(order_items.qty_ordered) AS `ordered_qty`,
`order_items`.`name` AS `order_items_name`,
`order_items`.`product_id` AS `entity_id`,
`e`.`entity_type_id`,
`e`.`attribute_set_id`,
`e`.`type_id`,
`e`.`sku`,
`e`.`has_options`,
`e`.`required_options`,
`e`.`created_at`,
`e`.`updated_at`
FROM
`sales_flat_order_item` AS `order_items`
INNER JOIN
`sales_flat_order` AS `order`
ON
`order`.entity_id = order_items.order_id
AND `order`.state <> 'canceled'
LEFT JOIN
`catalog_product_entity` AS `e`
ON
(e.type_id NOT IN ('grouped', 'configurable', 'bundle'))
AND e.entity_id = order_items.product_id
AND e.entity_type_id = 4
WHERE
(parent_item_id IS NULL)
GROUP BY
`order_items`.`product_id`
HAVING
(SUM(order_items.qty_ordered) > 0)
This part of the join is added in the function Mage_Reports_Model_Resource_Product_Collection::addOrderedQty
. What you could do would be to rewrite this and exclude this filter for product type.
NOTE: I am not sure what these results will show. I would like to think that the Magento developers did this for a reason, but I don't not know.
OTHER TIPS
I would say, that the reports only count "really" ordered products, not the child order items.