Can a CakePHP model change its table without being re-instantiated?

大憨熊 提交于 2020-01-04 21:45:45

问题


I'm working with an unchangeable legacy database schema where each instance of an object has its own table in the database with associated records. I need to change a model's useTable every time the model is instantiated, but retain Cake's nice caching and what not.

Say I have many pad objects, which each have several note objects (Note belongsTo Pad, Pad hasMany Note). Each pad has a record in the pads table, however every note has it's own table in a database (say entitled 'pad_{id}'). This schema is fixed and I must use it.

Right now I don't have to do any saving, so I do this in the model's before find to support reading:

function beforeFind($query_data) {
    if(empty($query_data['pad_id'])) {
        return false;
    } else {
        $this->useTable = $query_data['pad_id'];
        parent::__construct();
        return $query_data;
    }

}

This changes the model's table used in the database, and works fine when Core::debug > 0. However, when it's zero, I think CakePHP caches the model code and doesn't properly change the table. In any case, I get a 404 error when I visit /pads/view/{pad_id} or whatever action dynamically changes this table. I can't quite figure out what the exact error is, because it works fine when I turn debug on. So any pointers on debuging this issue would help also.

Thanks!


回答1:


You should be able to use setSource() to change the table the Model is using. $this->setSource('pad_x') will set the table to 'pad_x' and reset the model's schema. API reference




回答2:


Try var $persistModel = false; in your controller or in the AppController.

See: http://www.pseudocoder.com/archives/2009/03/17/8-ways-to-speed-up-cakephp-apps/



来源:https://stackoverflow.com/questions/1506101/can-a-cakephp-model-change-its-table-without-being-re-instantiated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!