Can a CakePHP model change its table without being

2019-07-11 07:37发布

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!

2条回答
Viruses.
2楼-- · 2019-07-11 08:06

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

查看更多
We Are One
3楼-- · 2019-07-11 08:22

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/

查看更多
登录 后发表回答