簡體   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