We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

请问 phalcon 是否支持数据库前缀 / Model table prefix in phalcon

数据库中每一个数据表都有一个前缀,比如 v1user 但是在命令 model 的时候应该去掉 v1 请问 phalcon 是否支持这样的前缀方式


In my database, each table has a prefix, as user_v1, but it must be removed in the model name

edited Aug '14

You have 2 options;

  • You can use $this->setSource('v1user'); in your Model's initialize() function

  • You can create a getSource() function on your Model, returning the table name

See https://phalcon-php-framework-documentation.readthedocs.org/en/latest/reference/models.html#creating-models

Examples;

<?php

class Robots extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->setSource("the_robots");
    }
}

class Robots extends \Phalcon\Mvc\Model {
    public function getSource() {
        return "the_robots";
    }
}


10.3k

这样可以修改一个模型,那如果我有N个模型,有没有办法可以统一配置这个前缀呢?



5.5k
Accepted
answer

I'm not sure if I understand, Google translate is helpful but not perfect.

Could you use a base class?

See https://forum.phalcon.io/discussion/2923/how-to-implement-database-the-table-like-this-prefix-tablename-i

Something like;

<?php

class BaseModel extends \Phalcon\Mvc\Model {
    public function getSource()
    {
        return 'v1'.str_tolower(get_class($this));
    }
}

class User extends BaseModel {
...
}


10.3k

thanks to @rvanderfeer yeah,you got it! this is what i want,thank you very much!