Reputation: 11485
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?
Upvotes: 2
Views: 2109
Reputation: 26403
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.
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->setSource("the_robots");
}
}
Upvotes: 1
Reputation: 106
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)));
}
Upvotes: 1
Reputation: 11485
You can override the getSource
method to set the prefix:
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:
trait CustomPrefix
{
public function getSource()
{
return 'my_' . strtolower(get_class($this));
}
}
then in your model:
class Users extends Phalcon\Mvc\Model
{
use CustomPrefix;
}
Upvotes: 3