繁体   English   中英

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

[英]Cakephp Model: How to use all table_name as singular?

我已经有一个数据库,其中包含约37个单数名称的表。 现在,我要制作一个cakephp应用程序,其控制器名称应为单数,而table_name应为单数。 我的cakephp版本是2.5.5

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

但是我认为对于这样数量的表,这不是更好的解决方案。

是否有任何捷径可让所有Models默认情况下都将table_name查找为单数语法?

该文档将表明:

public $useTable = 'your_singular';

在您的模型中就可以了。

使用烤壳

您可以简单地烘烤模型,shell会为不规则表名正确设置Model::$useTable属性,该不规则表名与模型名的默认表化变量不匹配。

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

或AppModel

默认情况下, 模型使用模型名称通过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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM