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?? 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 Jun 13, 2016 at 7:20
-
@RahulAgrawal I'm saying that you will have to use the model factory instead of the service contracts Jun 13, 2016 at 7:21
-
-