@@ -60,6 +60,14 @@ class Query extends Component implements QueryInterface
6060 */
6161 public $ options = [];
6262
63+ /**
64+ * Returns the connection used by this Query.
65+ * @param Connection $db Mongo connection.
66+ * @return Connection connection instance.
67+ */
68+ public function getDb ($ db = null ){
69+ return $ db === null ? $ db : Yii::$ app ->get ('mongodb ' );
70+ }
6371
6472 /**
6573 * Returns the Mongo collection for this query.
@@ -68,11 +76,7 @@ class Query extends Component implements QueryInterface
6876 */
6977 public function getCollection ($ db = null )
7078 {
71- if ($ db === null ) {
72- $ db = Yii::$ app ->get ('mongodb ' );
73- }
74-
75- return $ db ->getCollection ($ this ->from );
79+ return $ this ->getDb ($ db )->getCollection ($ this ->from );
7680 }
7781
7882 /**
@@ -210,9 +214,7 @@ public function buildCursor($db = null)
210214 */
211215 protected function fetchRows ($ all = true , $ db = null )
212216 {
213- if ($ db === null ) {
214- $ db = Yii::$ app ->get ('mongodb ' );
215- }
217+ $ db = $ this ->getDb ($ db );
216218 $ cursor = $ this ->buildCursor ($ db );
217219 $ token = 'fetch cursor id = ' . $ cursor ->getId ();
218220 if ($ db ->enableLogging ) {
@@ -288,7 +290,7 @@ public function batch($batchSize = 100, $db = null)
288290 'class ' => BatchQueryResult::className (),
289291 'query ' => $ this ,
290292 'batchSize ' => $ batchSize ,
291- 'db ' => $ db ,
293+ 'db ' => $ this -> getDb ( $ db ) ,
292294 'each ' => false ,
293295 ]);
294296 }
@@ -316,7 +318,7 @@ public function each($batchSize = 100, $db = null)
316318 'class ' => BatchQueryResult::className (),
317319 'query ' => $ this ,
318320 'batchSize ' => $ batchSize ,
319- 'db ' => $ db ,
321+ 'db ' => $ this -> getDb ( $ db ) ,
320322 'each ' => true ,
321323 ]);
322324 }
0 commit comments