1

I want to create a module that read reviews data from database table in magento and display it in the form of json. How can i read data from database in magento?

Raphael at Digital Pianism
70.8k37 gold badges192 silver badges357 bronze badges
asked Jun 13, 2016 at 7:05

1 Answer 1

2

To retrieve the review collection you can use \Magento\Review\Model\ResourceModel\Review\Product\Collection as unfortunately, as of now, Magento 2 does not provide a service layer for the Review module.

You can inject this class in your constructor:

protected $_productsFactory;
public function __construct(
 ...
 \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory $productsFactory,
 ...
) {
 ...
 $this->_productsFactory = $productsFactory;
 ...
}

Then you can call the following to get the collection:

$collection = $this->_productsFactory->create();

If you only want data for one product you can add:

$collection->addEntityFilter($productId);

Now to encode in JSON you need to inject the \Magento\Framework\Json\Helper\Data class in your constructor:

protected $_productsFactory;
protected $_jsonHelper;
public function __construct(
 ...
 \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory $productsFactory,
 \Magento\Framework\Json\Helper\Data $jsonHelper,
 ...
) {
 ...
 $this->_productsFactory = $productsFactory;
 $this->_jsonHelper = $jsonHelper;
 ...
}

Now in order to return a proper JSON I suggest you generate an array from the collection based on the data you need:

$result = [];
foreach ($collection as $review) {
 $result[] = ['title' => $review->getTitle(), 'nickname' => $review->getNickname(), 'detail' => $review->getDetail()];
}
$this->jsonHelper->jsonEncode($result);
answered Jun 13, 2016 at 7:17
17
  • So u r saying that i cannot access the review_detail table to get the list of reviews?? Commented Jun 13, 2016 at 7:20
  • @RahulAgrawal no that's not what I'm saying, what I posted will let you retrieve the list of reviews Commented Jun 13, 2016 at 7:20
  • @RahulAgrawal I'm saying that you will have to use the model factory instead of the service contracts Commented Jun 13, 2016 at 7:21
  • from where do i call the collection part Commented Jun 13, 2016 at 7:26
  • and i want the review of all the products Commented Jun 13, 2016 at 7:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.