queryAll works with wrong db

  1. I have a db connection function in base model for DAO with non default MySQL database "anotherdb":

    public function getDbConnection() {

        self::$db = new CDbConnection("mysql:host=localhost;dbname=anotherdb", "username", "password");

        self::$db->charset = 'utf8';

        self::$db->emulatePrepare = true;

        return self::$db;


and code in the child model:


        $dependency = new CDbCacheDependency('SELECT MAX(updatedAt) FROM Game');

        $command = parent::$db->cache(1000, $dependency)->createCommand($sql);        

        foreach ($command->queryAll() as $gameRow) {


This code throw an CDbException:

CDbCommand failed to execute the SQL statement: CDbCommand failed to execute the SQL statement: 

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'defaultdb.Game' doesn't exist. 

The SQL statement executed was: SELECT MAX(updatedAt) FROM Game. The SQL statement executed was: 

with strange trace message:

21:34:16.721687	trace	system.CModule	

Loading "db" application component

in /var/www/protected/models/GameController.php


in /var/www/protected/controllers/SiteController.php


in /var/www/index.php (13)

where "db" points to the defaultdb database in the config file.

When I use query instead queryAll or disable caching, everything works fine. I track down this exception to the line in code.google.com/p/yii/source/browse/tags/1.1.8/framework/db/CDbCommand.php#502 (sorry, I have no rights to embed links), and don’t sure this is right behaviour. How can I fix this?

  1. CDbCommand’s query method doesn’t support caching, does it? Why there are no big red signs warned about it? :)

I’ve changed dependency query to ‘SELECT MAX(updatedAt) FROM anotherdb.Game’, create db user with access rights to both defaultdb and anotherdb and add it to the config file in the “db” section instead defaultdb user. It works, but seems not very beautiful.

Update: Oh, I’m so stupid! CDbCacheDependency has a connectionID property. Didn’t try it yet, but I’m sure it will work. What a waste of time!