Question

In a multistore setup, I need to find products that are assigned to website A and website B.

The product collection has a addWebsiteFilter() method but unfortunately it doesn't serve this purpose, as can be seen in Mage_Catalog_Model_Resource_Product_Collection::_productLimitationJoinWebsite(), where the filter gets applied:

        $conditions[] = $this->getConnection()
            ->quoteInto('product_website.website_id IN(?)', $filters['website_ids']);

The query will match for all products that are assigned to any of the given websites. What is the best way to build a query for products that are present in multiple websites?

Was it helpful?

Solution

There it is. Given $websiteIds is an array of website ids:

$productCollection = Mage::getResourceModel('catalog/product_collection');
$productCollection->addWebsiteFilter($websiteIds);
$productCollection->getSelect()
    ->having('COUNT(website_id) = ?', count($websiteIds))
    ->distinct(false)
    ->group('e.entity_id');

I removed DISTINCT and grouped by product instead to be able to COUNT the number of joined websites. If it is equal to the total number of filtered websites, the product is assigned to all of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top