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?
1 Answer
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); - So u r saying that i cannot access the review_detail table to get the list of reviews??Rahul Agrawal– Rahul Agrawal2016-06-13 07:20:08 +00:00Commented 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 reviewsRaphael at Digital Pianism– Raphael at Digital Pianism2016-06-13 07:20:52 +00:00Commented Jun 13, 2016 at 7:20
- @RahulAgrawal I'm saying that you will have to use the model factory instead of the service contractsRaphael at Digital Pianism– Raphael at Digital Pianism2016-06-13 07:21:28 +00:00Commented Jun 13, 2016 at 7:21
- from where do i call the collection partRahul Agrawal– Rahul Agrawal2016-06-13 07:26:32 +00:00Commented Jun 13, 2016 at 7:26
- and i want the review of all the productsRahul Agrawal– Rahul Agrawal2016-06-13 07:27:10 +00:00Commented Jun 13, 2016 at 7:27