1

I've found in a template file, a code like the one below:

$collection = Mage::getModel('catalog/product_link')
            ->getCollection()
            ->addFieldToFilter('product_id', $_product->getId());

It's used to display additional tabs in product view if($collection->count()), the problem is that it doesn't care if products in collection are enabled or disabled.

What would be the easiest way to count, using "the same code", only the enabled products?

2 Answers 2

0

I only see two solutions here, but none of them are ideal in terms of performance I think.

Solution 1 : dirty loop and count

$count = 0;
foreach ($collection as $product) {
     if ($product->getStatus() == Mage_Catalog_Model_Product_Status::STATUS_ENABLED) {
         $count++;
     }
}

Solution 2: use another collection

$clone = clone $collection;
$clone->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$count = $clone->getSize();
1
  • Solution 1 as you said, is not a good idea, the second, it doesn't work
    – Di36o
    Commented Apr 21, 2017 at 11:19
0

Well i am not sure if thats possible at all.

Use this to get enabled products only

    $collection->getSelect()->join(
    'catalog_product_entity_int',
    // note this join clause! Here main table is catalog_product_link
    'main_table.product_id = catalog_product_entity_int.entity_id'
)
->where("attribute_id = 80 and catalog_product_entity_int.value= 1");

Or go through the loop find all enabled products. Store in an array. Get a count. Or use increment operator like Raphael says.

4
  • It doesn't work, it throws SQLSTATE[42S22]: Column not found: 1054 Unknown column 'status' in 'where clause'
    – Di36o
    Commented Apr 21, 2017 at 11:19
  • Updated my answer. catalog_product_entity_int stores the status for products. You need to join that table and filter your collection based on that. Commented Apr 21, 2017 at 11:36
  • I tried, but it "doesn't" work as I spected, look, this is the query I got: SELECT main_table.*, catalog_product_entity_int.* FROM catalog_product_link AS main_table INNER JOIN catalog_product_entity_int ON main_table.product_id = catalog_product_entity_int.entity_id WHERE (product_id = '173031') AND (catalog_product_entity_int.value=1) Look at the screenshot table in top is the result of the query, below the "product", the attribute_id 80 is the status i.imgur.com/WoENI6y.png
    – Di36o
    Commented Apr 21, 2017 at 12:01
  • Well i think there should be another condition in where clause. Try now. Commented Apr 21, 2017 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.