tags:

views:

44

answers:

2

Hi all,

Today I've got a problem when I tried using following code to alter the model attribute in the controller

function userlist($trigger = 1)
{
    if($trigger == 1)
    {
        $this->User->useTable = 'betausers'; //'betausers' is completely the same structure as table 'users'
    }
    $users = $this->User->find('all');
    debug($users);
}

And the model file is

class User extends AppModel
{
    var $name = "User";
    //var $useTable = 'betausers';

    function beforeFind()   //only for debug
    {
        debug($this->useTable);
    }
}

The debug message in the model showed the userTable attribute had been changed to betausers.And It was supposed to show all records in table betausers.However,I still got the data in the users,which quite confused me.And I hope someone can show me some directions to solve this problem.

Regards

+1  A: 

The table to use is "fixed" when the model is loaded/instantiated. At that time a DB connection object is created, the table schema is being checked and a lot of other things happen. You can change that variable later all you want, Cake is not looking at it anymore after that point.

One model should be associated with one table, and that association shouldn't change during runtime. You'll need to make another model BetaUser and dynamically change the model you're using. Or rethink your database schema, a simple flag to distinguish beta users from regular users within the users table may be better than a whole new table.

deceze
+2  A: 

Model::useTable is only consulted during model instantiation (see the API documentation for Model::__construct). If you want to change the model's table on the fly, you should use Model::setSource:

if ( $trigger == 1 ) {
    $this->User->setSource('betausers');
}
Daniel Wright