简体   繁体   中英

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

A common task for me when I'm writing CakePHP applications is to type out an SQL file and write it into the database before running bake to generate some scaffolding. This is one of the very few gripes I have with CakePHP - doing this ties me into MySQL, and I'm wondering if there's a better way to do it through code. As an example, in some frameworks I can define the columns that my model uses along with the datatype and such, and then run a command through an admin interface to "build" the database based on what what's presented in the code. It will do this on whatever database is sitting behind the framework.

Is there a way for CakePHP 2.x can do something like this? I want to write out the database schema in my Model code and run a command like bake to automatically generate the tables and columns that I need. After diving into the cookbook docs, the _schema attribute seems to do what I want to do:

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

but there are no examples explaining what I would I do from there. Does the _schema attribute serve a different purpose? Any help would be appreciated!

not from your $_schema array itself. but creating and using a schema file schema.php in /APP/Config/Schema.

you can then run the bake command "cake schema create" which will then "Drop and create tables based on the schema file."

I might then look sth like this:

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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