1

Coming in to trouble while getting correct data from my wishlist:

/** 
    @var \Magento\Wishlist\Model\Wishlist $_wishlist 
    @var \Magento\Customer\Model\Session $_customerSession
*/
$wishlistCollection = $this->_wishlist->loadByCustomerId($this->_customerSession->getCustomerId(), true)->getItemCollection();
foreach($wishlistCollection as $wishedItem){
    /** @var \Magento\Catalog\Model\Product $_product; */
    $product = $this->_product->setStoreId($wishedItem->getStoreId())->load($wishedItem->getProductId);
    /** @var \Magento\Review\Model\Rating $_rating; */
    $rating = $this->_rating->getEntitySummary($wishedItem->getProductId(), true);
    $ratingValue = NULL;
    if($rating->getSum() && $rating->getCount()) $ratingValue = $rating->getSum()/$rating->getCount();

    echo $product->getName();
    echo $product->getSku();
    echo $product->getProductUrl();
    echo $ratingValue;
}

product 1 was clone of the original product. Product 1 has rating while original has no reviews.Review to product 1 was added after dublicating.

while in the loop product name and sku are different, but url and rating values are the same, so not sure what is wrong here.

1 Answer 1

0

Your way to load products reuses the same product model. In that way you will have data of the previous product in cases in which the new product for example does not a have data for a specific attribute.

You should use a product factory instead for loading the product in the following way:

protected $_productFactory;

//inject product factory in constructor
public function __construct(
    [...]
    \Magento\Catalog\Model\ProductFactory $productFactory
    )
   {
       [...]
       $this->_productFactory = $productFactory;
   }

   [...]
   //load product
   $product = $this->_productFactory->create()->setStoreId($wishedItem->getStoreId())->load($wishedItem->getProductId);

Or at least call reset() on your product model before loading a new product:

   $product = $this->_product->reset()->setStoreId($wishedItem->getStoreId())->load($wishedItem->getProductId);
3
  • Thanks, now only rating problem remains. Even with reset it shows same values. Apr 15, 2019 at 11:09
  • try the same approach and use a factory insetad of the rate model: $rating = $this->_ratingFactory->create(); and inject \Magento\Review\Model\RatingFactory $ratingFactory
    – HelgeB
    Apr 15, 2019 at 11:11
  • thx, reset was working too but problem was with cache.. Apr 15, 2019 at 11:23

Your Answer

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

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