1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:
26:
27:
28: 29: 30: 31: 32: 33: 34:
35: class Mage_Reports_Model_Resource_Review_Product_Collection extends Mage_Catalog_Model_Resource_Product_Collection
36: {
37: protected function _construct()
38: {
39: parent::_construct();
40: $this->_useAnalyticFunction = true;
41: }
42: 43: 44: 45: 46:
47: public function joinReview()
48: {
49: $helper = Mage::getResourceHelper('core');
50:
51: $subSelect = clone $this->getSelect();
52: $subSelect->reset()
53: ->from(array('rev' => $this->getTable('review/review')), 'COUNT(DISTINCT rev.review_id)')
54: ->where('e.entity_id = rev.entity_pk_value');
55:
56: $this->addAttributeToSelect('name');
57:
58: $this->getSelect()
59: ->join(
60: array('r' => $this->getTable('review/review')),
61: 'e.entity_id = r.entity_pk_value',
62: array(
63: 'review_cnt' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
64: 'last_created' => 'MAX(r.created_at)',))
65: ->group('e.entity_id');
66:
67: $joinCondition = array(
68: 'e.entity_id = table_rating.entity_pk_value',
69: $this->getConnection()->quoteInto('table_rating.store_id > ?', 0)
70: );
71:
72: 73: 74:
75: $groupByCondition = $this->getSelect()->getPart(Zend_Db_Select::GROUP);
76: $percentField = $this->getConnection()->quoteIdentifier('table_rating.percent');
77: $sumPercentField = $helper->prepareColumn("SUM({$percentField})", $groupByCondition);
78: $sumPercentApproved = $helper->prepareColumn('SUM(table_rating.percent_approved)', $groupByCondition);
79: $countRatingId = $helper->prepareColumn('COUNT(table_rating.rating_id)', $groupByCondition);
80:
81: $this->getSelect()
82: ->joinLeft(
83: array('table_rating' => $this->getTable('rating/rating_vote_aggregated')),
84: implode(' AND ', $joinCondition),
85: array(
86: 'avg_rating' => sprintf('%s/%s', $sumPercentField, $countRatingId),
87: 'avg_rating_approved' => sprintf('%s/%s', $sumPercentApproved, $countRatingId),
88: ));
89:
90: return $this;
91: }
92:
93: 94: 95: 96: 97: 98: 99:
100: public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC)
101: {
102: if (in_array($attribute, array('review_cnt', 'last_created', 'avg_rating', 'avg_rating_approved'))) {
103: $this->getSelect()->order($attribute.' '.$dir);
104: return $this;
105: }
106:
107: return parent::addAttributeToSort($attribute, $dir);
108: }
109:
110: 111: 112: 113: 114:
115: public function getSelectCountSql()
116: {
117: $this->_renderFilters();
118:
119:
120: $select = clone $this->getSelect();
121: $select->reset(Zend_Db_Select::ORDER);
122: $select->reset(Zend_Db_Select::LIMIT_COUNT);
123: $select->reset(Zend_Db_Select::LIMIT_OFFSET);
124: $select->reset(Zend_Db_Select::COLUMNS);
125: $select->resetJoinLeft();
126: $select->columns(new Zend_Db_Expr('1'));
127:
128:
129: $countSelect = clone $select;
130: $countSelect->reset();
131: $countSelect->from($select, "COUNT(*)");
132:
133: return $countSelect;
134: }
135: }
136: