CakePHP模型可以改变它的表,而不会被重新实例化? [英] Can a CakePHP model change its table without being re-instantiated?

查看:187
本文介绍了CakePHP模型可以改变它的表,而不会被重新实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个不可改变的遗留数据库模式,其中对象的每个实例在数据库中都有自己的具有关联记录的表。我需要改变模型的 useTable 每次模型被实例化,但保留Cake的漂亮的缓存,什么不。

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.

说我有很多pad对象,每个都有几个音符对象(注意属于Pad,Pad有很多注释)。每个pad在pad表中有一个记录,然而每个笔记在数据库中有它自己的表(称为'pad_ {id}')。这个模式是固定的,我必须使用它。

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

}

这会更改模型的表数据库,并且工作正常时 Core :: debug> 0 。但是,当它为零时,我认为CakePHP缓存模型代码,并没有正确更改表。在任何情况下,当我访问/ pads / view / {pad_id}或任何动作动态更改此表时,我收到404错误。我不能弄清楚确切的错误是什么,因为它工作正常,当我打开调试。所以任何调试这个问题的指针也会有帮助。

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.

谢谢!

推荐答案

您应该可以使用 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

这篇关于CakePHP模型可以改变它的表,而不会被重新实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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