Product Collection – Fix Issue with Not Getting All Products

collection;modelproduct

I am using a pretty basic product collection but it isn't returning all products in my store. Please find the code below:

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

This returns 4,972 products, but there is a total of 7,265 products in my store which is shown under Manage Products in the admin panel.

Has anyone experienced this before and possibly knows a way to fix this?

Thanks!

EDIT

I have also ran the following code to see the SQL being executed:

echo $collection->getSelect();

This has returned the following SQL:

SELECT 1 AS `status`, `e`.`entity_id`, `e`.`type_id`, `e`.`attribute_set_id`, `e`.`entity_id`, `e`.`attribute_set_id`, `e`.`type_id`, `e`.`cost`, `e`.`created_at`, `e`.`gift_message_available`, `e`.`has_options`, `e`.`image_label`, `e`.`is_recurring`, `e`.`links_exist`, `e`.`links_purchased_separately`, `e`.`links_title`, `e`.`msrp`, `e`.`msrp_display_actual_price_type`, `e`.`msrp_enabled`, `e`.`name`, `e`.`news_from_date`, `e`.`news_to_date`, `e`.`price`, `e`.`price_type`, `e`.`price_view`, `e`.`recurring_profile`, `e`.`required_options`, `e`.`shipment_type`, `e`.`short_description`, `e`.`sku`, `e`.`sku_type`, `e`.`small_image`, `e`.`small_image_label`, `e`.`special_from_date`, `e`.`special_price`, `e`.`special_to_date`, `e`.`tax_class_id`, `e`.`thumbnail`, `e`.`thumbnail_label`, `e`.`updated_at`, `e`.`url_key`, `e`.`url_path`, `e`.`visibility`, `e`.`weight`, `e`.`weight_type`, `e`.`manufacturer`, `e`.`prmotional_text`, `e`.`brand`, `e`.`brand_value` FROM `shop_catalog_product_flat_1` AS `e`

EDIT #2

I have just amended all my products to be included in my main store view (ID 1), but still no luck.

I've also noticed the total number of products changes slightly, it has gone from 4,972 to 4,971 to 4,973.

Best Answer

When you get a collection of products and you have it in the system configuration to use the product flat table, the collection will retrieve products from the flat table of the corresponding store view.

Looking at your query, it's retrieving your products from the product flat table of store ID 1 (shop_catalog_product_flat_1) for some reason. If you want to retrieve all products as you see in the admin, then you can force a store in your independent script using the following.

Mage::app()->setCurrentStore(0)

This will ensure your collection will retrieve products from the main product table, shop_catalog_product_entity in your case.

Related Topic