[英]Table prefix configuration in Phalcon Model
I would like to set up a table prefix for all my models, since this is how it is designed in the database. 我想为所有模型设置一个表前缀,因为这是在数据库中设计的方式。
How can I achieve that? 我该如何实现?
You can override the getSource
method to set the prefix: 您可以重写
getSource
方法来设置前缀:
class Users extends Phalcon\Mvc\Model
{
public function getSource()
{
return 'my_' . 'users';
}
}
Or, you can set a base model class to set the table prefix for all models: 或者,您可以设置基本模型类来为所有模型设置表前缀:
class BaseModel extends Phalcon\Mvc\Model
{
public function getSource()
{
return 'my_' . strtolower(get_class($this));
}
}
and extend all models from that 并从中扩展所有模型
class Users extends BaseModel
{
}
or in PHP 5.4 you can create a trait: 或在PHP 5.4中,您可以创建一个特征:
trait CustomPrefix
{
public function getSource()
{
return 'my_' . strtolower(get_class($this));
}
}
then in your model: 然后在您的模型中:
class Users extends Phalcon\Mvc\Model
{
use CustomPrefix;
}
Also, if you have tables with underscores "_" you could write it like that: 另外,如果您的表带有下划线“ _”,则可以这样写:
public function getSource()
{
return 'my_'.strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', get_class($this)));
}
you can also add all your settings to initialize function. 您还可以添加所有设置以初始化功能。 If you have any connection between models like one-one many-many one-many you will define them also in initialize method.
如果模型之间有任何联系,例如一对多,一对多,则也可以在initialize方法中定义它们。
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->setSource("the_robots");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.