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'];
  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.


+1  A: 

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/

A good temporary solution, however I don't want to shortcut model persistence, I want to use it for the noticeable performance increase and just change the table used in all the queries. I think I might have to modify the base model class, but that doesn't sound very Cake like to me.
You can do this the cake way when you extend the model behavior!
+3  A: 

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

Mark Story
Mark Story, you do amazing things.