Magento – Magento get reviews filtered by product

magento-1.9review

I am trying to get product reviews filtered by Product Id, but in the product which doesn't have any reviews added, the reviews count still shows 2 reviews.

This means review collection filter by Product Id isn't working.

Below is the code I am using to get Review collection.

<?php
$_product = $this->getProduct();
$productId = $_product->getId();
$reviews = Mage::getModel('review/review')->getResourceCollection()
        ->addStoreFilter(Mage::app()->getStore()->getId())
        ->addEntityFilter('product', $productId)
        ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
        ->setDateOrder()
        ->addRateVotes();
$avg = 0;
$ratings = array();
if (count($reviews) > 0){
foreach ($reviews as $_review): ?>
<?php foreach( $_review->getRatingVotes() as $_vote ): ?>
<?php $ratings[] = $_vote->getPercent(); ?>
<?php endforeach; ?>
<?php endforeach;
$avg = array_sum($ratings)/count($ratings); }
?>

Can somebody let me know what might be going wrong with this ?

Best Answer

There's nothing wrong with the posted code. I've checked it against 1.9.1.0 with sample data and using productId 337. I get a count of 6 each time and have been trying to break it, unsuccessfully (test script is below).

That means the error is in the code that you're not showing: the actual count() in the template file.

Test code used:

<?php
require_once('app/Mage.php');
Mage::app('default');
umask(0);
Mage::setIsDeveloperMode(true);
if( extension_loaded('xdebug') )
{
    ini_set('xdebug.cli_color', true);
    ini_set('xdebug.var_display_max_data', -1); // unlimited
}
$productId = 337;
$reviews = Mage::getModel('review/review')->getCollection()
    ->addStoreFilter(Mage::app()->getStore()->getId())
    ->addEntityFilter('product', $productId)
    ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
    ->setDateOrder()
    ->addRateVotes();

echo((string)$reviews->getSelect().PHP_EOL);
var_dump(count($reviews->getItems()));
var_dump($reviews->count());
echo(str_repeat('-', 80).PHP_EOL);
/** @var Mage_Review_Model_Review $review */
foreach($reviews AS $review)
{
    /** @var Mage_Rating_Model_Resource_Rating_Option_Vote_Collection $votes */
    $votes = $review->getRatingVotes();
    $total = 0;
    foreach($votes AS $vote)
    {
        $total += $vote->getPercent();
    }
    $avg = $total / count($votes);
    var_dump($total, count($votes), $avg);
    echo(PHP_EOL);
}
Related Topic