99class Tag extends \Magento \Framework \Model \ResourceModel \Db \AbstractDb
1010{
1111 protected $ _tagProductTable = '' ;
12-
12+
1313 protected function _construct ()
1414 {
1515 $ this ->_init ('lof_producttags_tag ' , 'tag_id ' );
1616 }
17-
17+
1818 /**
1919 * Process page data after saving
2020 *
@@ -69,7 +69,7 @@ protected function _saveTagProducts($tag)
6969
7070 $ connection = $ this ->getConnection ();
7171
72- /**
72+ /**
7373 * Delete products from tag
7474 */
7575 if (!empty ($ delete )) {
@@ -107,7 +107,7 @@ protected function _saveTagProducts($tag)
107107
108108 foreach ($ newPositions as $ delta => $ productIds ) {
109109 $ bind = ['position ' => new \Zend_Db_Expr ("position + ( {$ delta }) " )];
110- $ where = ['tag_id = ? ' => (int )$ id , 'product_id IN (?) ' => $ productIds ];
110+ $ where = ['tag_id = ? ' => (int )$ id , 'product_id IN (?) ' => $ productIds ];
111111 $ connection ->update ($ this ->getTagProductTable (), $ bind , $ where );
112112 }
113113 }
@@ -125,8 +125,36 @@ protected function _saveTagProducts($tag)
125125 $ tag ->setAffectedProductIds ($ productIds );
126126 }
127127
128+ $ productCount = $ this ->getProductCount ($ tag );
129+ $ tableName = $ this ->getTable ('lof_producttags_tag ' ); //gives table name with prefix
130+ $ connection ->update (
131+ ['main_table ' => $ tableName ],
132+ ['number_products ' => (int )$ productCount ],['tag_id = ? ' => (int )$ id ]);
128133 return $ this ;
129134 }
135+ /**
136+ * Count product selected on Product Tags
137+ */
138+ public function getProductCount ($ tag )
139+ {
140+ $ productTable = $ this ->getTable ('lof_producttags_product ' );
141+
142+ $ select = $ this ->getConnection ()->select ()->from (
143+ ['main_table ' => $ productTable ],
144+ [new \Zend_Db_Expr ('COUNT(main_table.product_id) ' )]
145+ )->where (
146+ 'main_table.tag_id = :tag_id '
147+ );
148+
149+ $ bind = ['tag_id ' => (int )$ tag ->getId ()];
150+ $ counts = $ this ->getConnection ()->fetchOne ($ select , $ bind );
151+
152+ return intval ($ counts );
153+ }
154+
155+ /**
156+ * Save Tag Store
157+ */
130158 protected function _saveTagStores ($ tag )
131159 {
132160 $ oldStores = $ this ->lookupStoreIds ($ tag ->getId ());
@@ -150,9 +178,7 @@ protected function _saveTagStores($tag)
150178 }
151179 return $ this ;
152180 }
153-
154181
155-
156182 /**
157183 * Perform operations after object load
158184 *
@@ -164,6 +190,8 @@ protected function _afterLoad(\Magento\Framework\Model\AbstractModel $object)
164190 if ($ object ->getId ()) {
165191 $ stores = $ this ->lookupStoreIds ($ object ->getId ());
166192 $ object ->setData ('store_id ' , $ stores );
193+ // $productCount = $this->getProductCount($object);
194+ // print_r($productCount);die();
167195 }
168196 return parent ::_afterLoad ($ object );
169197 }
0 commit comments