更改控制器中的模型属性的问题 [英] Problem with altering model attributes in controller

查看:97
本文介绍了更改控制器中的模型属性的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我有一个问题,当我尝试使用以下代码来改变控制器中的模型属性

  function userlist ($ trigger = 1)
{
if($ trigger == 1)
{
$ this-> User-> useTable ='betausers'; //'betausers'与表'users'完全相同的结构
}
$ users = $ this-> User-> find('all');
debug($ users);
}

而且模型文件是

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

function beforeFind()//仅用于调试
{
debug($ this-> useTable);
}
}

模型中的调试消息显示 userTable 属性已更改为 betausers 。并且应显示表中的所有记录 betausers 。但是,我仍然得到的数据在 users ,这很困惑我。我希望有人可以给我一些方向来解决这个问题。 / p>

尊敬

解决方案

Model :: useTable 仅在模型实例化期间参考(请参阅模型的API文档:: __ construct )。如果您想要即时更改模型的表格,则应该使用 Model :: setSource

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


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

解决方案

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');
}

这篇关于更改控制器中的模型属性的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆