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_Tag_Model_Entity_Customer_Collection extends Mage_Customer_Model_Entity_Customer_Collection
36: {
37: protected $_tagTable;
38: protected $_tagRelTable;
39:
40: public function __construct()
41: {
42: $resource = Mage::getSingleton('core/resource');
43: parent::__construct();
44: $this->_tagTable = $resource->getTableName('tag/tag');
45: $this->_tagRelTable = $resource->getTableName('tag/tag_relation');
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56: }
57:
58: public function addTagFilter($tagId)
59: {
60: $this->joinField('tag_tag_id', $this->_tagRelTable, 'tag_id', 'customer_id=entity_id');
61: $this->getSelect()->where($this->_getAttributeTableAlias('tag_tag_id') . '.tag_id=?', $tagId);
62: return $this;
63: }
64:
65: public function addProductFilter($productId)
66: {
67: $this->joinField('tag_product_id', $this->_tagRelTable, 'product_id', 'customer_id=entity_id');
68: $this->getSelect()->where($this->_getAttributeTableAlias('tag_product_id') . '.product_id=?', $productId);
69: return $this;
70: }
71:
72: public function load($printQuery = false, $logQuery = false)
73: {
74: parent::load($printQuery, $logQuery);
75: $this->_loadTags($printQuery, $logQuery);
76: return $this;
77: }
78:
79: protected function _loadTags($printQuery = false, $logQuery = false)
80: {
81: if (empty($this->_items)) {
82: return $this;
83: }
84: $customerIds = array();
85: foreach ($this->getItems() as $item) {
86: $customerIds[] = $item->getId();
87: }
88: $this->getSelect()->reset()
89: ->from(array('tr' => $this->_tagRelTable), array('*','total_used' => 'count(tr.tag_relation_id)'))
90: ->joinLeft(array('t' => $this->_tagTable),'t.tag_id=tr.tag_id')
91: ->group(array('tr.customer_id', 't.tag_id'))
92: ->where('tr.customer_id in (?)',$customerIds)
93: ;
94: $this->printLogQuery($printQuery, $logQuery);
95:
96: $tags = array();
97: $data = $this->_read->fetchAll($this->getSelect());
98: foreach ($data as $row) {
99: if (!isset($tags[ $row['customer_id'] ])) {
100: $tags[ $row['customer_id'] ] = array();
101: }
102: $tags[ $row['customer_id'] ][] = $row;
103: }
104: foreach ($this->getItems() as $item) {
105: if (isset($tags[$item->getId()])) {
106: $item->setData('tags', $tags[$item->getId()]);
107: }
108: }
109: return $this;
110: }
111:
112: }
113: