首页 文章

Cakephp模型:如何将所有table_name用作单数?

提问于
浏览
0

我有一个现有的数据库,有大约37个表,这些表是单数名称 . 现在,我要制作一个cakephp应用程序,控制器名称应该是单数的,table_name已经是单数 . 我的cakephp版本是2.5.5

我可以使用public $ useTable =“table_name”或Inflector :: rules('plural',array('irregular'=> array('table_name'=>'table_name')));

但我认为对于这么多的表来说这不是一个更好的解决方案 .

是否有任何快捷方式,以便所有模型默认情况下将table_name作为单数语法?

2 回答

  • 2

    文件将揭示:

    public $useTable = 'your_singular';
    

    在你的模型中做到了 .

  • 4

    使用烘烤壳

    您可以简单地烘焙模型,shell将为不规则表名称正确设置 Model::$useTable 属性,该名称与模型名称的默认表格化变体不匹配 .

    另见 http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

    或AppModel

    默认models are using the model name to create the table name使用Inflector::tabelize() .

    因此,一种方法是做类似的事情,并在 AppModel 构造函数中为 $useTable 动态设置单一化的表名 .

    这是一个(未经测试的)示例,说明了我在说什么

    class AppModel extends Model {
        public function __construct($id = false, $table = null, $ds = null) {
            if (is_array($id)) {
                extract(array_merge(array('name' => $this->name), $id));
            }
    
            if ($this->name === null) {
                $this->name = (isset($name) ? $name : get_class($this));
            }
    
            // set underscored model name as table name
            // ex TableName results in table_name
            $this->useTable = Inflector::underscore($this->name);
    
            parent::__construct($id, $table, $ds);
        }
    }
    

相关问题