CakePHP 模型可以在不重新实例化的情况下更改其表吗?
我正在使用不可更改的旧数据库模式,其中对象的每个实例在数据库中都有自己的表以及关联的记录。每次实例化模型时,我都需要更改模型的 useTable
,但保留 Cake 的良好缓存等等。
假设我有很多 pad 对象,每个 pad 对象都有几个 note 对象(Note 属于 Pad,Pad hasMany Note)。每个 pad 在 pad 表中都有一条记录,但是每个音符在数据库中都有自己的表(例如标题为“pad_{id}”)。这个模式是固定的,我必须使用它。
现在我不需要做任何保存,所以我在模型的 before find 中执行此操作以支持阅读:
function beforeFind($query_data) {
if(empty($query_data['pad_id'])) {
return false;
} else {
$this->useTable = $query_data['pad_id'];
parent::__construct();
return $query_data;
}
}
这会更改数据库中使用的模型表,并且当 Core::debug > 时工作正常。 0 。但是,当它为零时,我认为 CakePHP 会缓存模型代码并且不会正确更改表。无论如何,当我访问 /pads/view/{pad_id} 或任何动态更改此表的操作时,我都会收到 404 错误。我不太清楚确切的错误是什么,因为当我打开调试时它工作正常。因此,任何有关调试此问题的指示也会有所帮助。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用
setSource()
更改模型正在使用的表。$this->setSource('pad_x')
会将表设置为“pad_x”并重置模型的架构。 API 参考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在控制器或 AppController 中尝试
var $persistModel = false;
。请参阅: http:// /www.pseudocoder.com/archives/2009/03/17/8-ways-to-speed-up-cakephp-apps/
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/