Join in magento 2 Ratings and Review
-
19-02-2021 - |
Question
I am trying to fecth data form review and rating_option_vote. i need all values of rating and all Rating count group by Rating Id.
public function getRatingSummeryByAttribute($currentProductId)
{
$attributesValues = $this->ratingColFactory->create()
->addFieldToSelect('rating_id')
->addFieldToSelect('rating_code')
->getData();
if ($attributesValues)
{
$totalRatingRecord = $this->_ratingFactory
->addFieldToFilter ('entity_pk_value', $currentProductId);
$totalRatingRecord->getSelect()
->columns('SUM(value) as sum_vales')
->columns('count(rating_id) as total_rating')
->group('rating_id')->join(
[
'review' => 'review'
],
"main_table.review_id = review.review_id"
)->where('status_id = 1')
;
echo $totalRatingRecord->getSelect()->__toString();
Query Printed
SELECT
main_table
., SUM(value) ASsum_vales
, count(rating_id) AStotal_rating
,review
. FROMrating_option_vote
ASmain_table
INNER JOINreview
ON main_table.review_id = review.review_id WHERE (entity_pk_value
= '14') AND (status_id = 1) GROUP BYrating_id
Solution
Two table column has a common column name is entity_pk_value. Try following way:
public function getRatingSummeryByAttribute($currentProductId)
{
$attributesValues = $this->ratingColFactory->create()
->addFieldToSelect('rating_id')
->addFieldToSelect('rating_code')
->getData();
if ($attributesValues)
{
$totalRatingRecord = $this->_ratingFactory
->addFieldToFilter ('main_table.entity_pk_value', $currentProductId);
$totalRatingRecord->getSelect()
->columns('SUM(value) as sum_vales')
->columns('count(rating_id) as total_rating')
->group('rating_id')->join(
[
'review' => 'review'
],
"main_table.review_id = review.review_id"
)->where('status_id = 1')
;
echo $totalRatingRecord->getSelect()->__toString();
And query
SELECT main_table.*, SUM(value) AS sum_vales, count(rating_id) AS total_rating FROM rating_option_vote AS main_table INNER JOIN review ON main_table.review_id = review.review_id WHERE (main_table.entity_pk_value = '14') AND (status_id = 1) GROUP BY rating_id
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange