Magento – How to Create product rating programmatically

magento-1.7ratingsreview

I want to create product review and rating programmatically. I was able to create review programmatically by the following code snippet

<?php
ini_set('memory_limit', '128M');
require_once 'app/Mage.php';
Mage::app();
Mage::app()->setCurrentStore(1); //desired store id
$review = Mage::getModel('review/review');
$review->setEntityPkValue(1);//product id
$review->setStatusId(1);
$review->setTitle("mytitle");
$review->setDetail("mydetail");
$review->setEntityId(1);                                      
$review->setStoreId(Mage::app()->getStore()->getId());      //storeview              
$review->setStatusId(1); //approved
$review->setCustomerId(1);
$review->setNickname("Menickname");
$review->setReviewId($review->getId());
$review->setStores(array(Mage::app()->getStore()->getId()));
$review->save();
$review->aggregate();
?>

But I don't know how to create rating programmatically. I'm totally blank about it. Can anyone help on this?

Best Answer

You need to loop through all the voting options and create a rating for each option selected and like it back to your review.

foreach ($rating as $ratingId => $optionId) {
     Mage::getModel('rating/rating')
          ->setRatingId($ratingId)
          ->setReviewId($review->getId())
          ->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())
          ->addOptionVote($optionId, $product->getId());
}

To get all the ratings you can use the rating's resource collection:

    $ratingCollection = Mage::getModel('rating/rating')
        ->getResourceCollection()
        ->addEntityFilter('product')
        ->setPositionOrder()
        ->addRatingPerStoreName(Mage::app()->getStore()->getId())
        ->setStoreFilter(Mage::app()->getStore()->getId())
        ->load()
        ->addOptionToItems();

Then for each rating object you can call getOptions() to get each possible option for each rating.