Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top