繁体   English   中英

CakePHP可以从Model上的_schema属性生成我的数据库表吗?

[英]Can CakePHP generate my database tables from the _schema attribute on the Model?

当我编写CakePHP应用程序时,我的一个常见任务是键入一个SQL文件并将其写入数据库,然后再运行bake以生成一些脚手架。 这是我与CakePHP的极少数抱怨之一 - 这使我与MySQL联系起来,我想知道是否有更好的方法通过代码来完成它。 例如,在某些框架中,我可以定义模型使用的列以及数据类型等,然后通过管理界面运行命令,根据代码中显示的内容“构建”数据库。 它将在框架后面的任何数据库上执行此操作。

CakePHP 2.x有没有办法可以做到这样的事情? 我想在我的Model代码中写出数据库模式,并运行像bake这样的命令来自动生成我需要的表和列。 在深入了解cookbook文档后, _schema属性似乎做了我想做的事情:

class Post{
  public $_schema = array(
    'title' => array('type'=>'text'),
    'description' => array('type'=>'text'),
    'author' => array('type'=>'text')
  );
}

但没有例子说明我将从那里做什么。 _schema属性是否有不同的用途? 任何帮助,将不胜感激!

而不是你的$ _schema数组本身。 但在/ APP / Config / Schema中创建和使用模式文件schema.php

然后,您可以运行bake命令“cake schema create”,然后“根据模式文件删除并创建表”。

我可能会看起来像这样:

class YourSchema extends CakeSchema {

    public $addresses = array(
        'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
        'contact_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 10),
        'type' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 2),
        'status' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 2),
        'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'collate' => 'utf8_unicode_ci', 'comment' => 'redundant', 'charset' => 'utf8'),
        'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
        'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
        'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
        'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'MyISAM')
    )

    // more tables...
}

暂无
暂无

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

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