Phalcon 数据库迁移
数据库迁移很重要,原因如下:
数据库迁移有助于在指定的存储类型之间传输数据;
数据库迁移是指基于 Web 的应用程序从一个平台迁移到另一个平台的上下文;
此过程通常用于跟踪过时的数据。
Phalcon 执行数据库迁移过程如下:
步骤1: 在xampp/wamp目录中创建一个名为“dbProject”的项目:
步骤2: 用适当的数据库连接配置项目:
<?php /* * Modified: preppend directory path of current file, because of this file own different ENV under between Apache and command line. * 注意: please remove this comment. */ defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..')); defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app'); return new \Phalcon\Config(['database' => [ 'adapter' => 'Mysql', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'demodb', 'charset' => 'utf8', ], 'application' => [ 'appDir' => APP_PATH . '/', 'controllersDir' => APP_PATH . '/controllers/', 'modelsDir' => APP_PATH . '/models/', 'migrationsDir' => APP_PATH . '/migrations/', 'viewsDir' => APP_PATH . '/views/','pluginsDir' => APP_PATH . '/plugins/', 'libraryDir' => APP_PATH . '/library/', 'cacheDir' => BASE_PATH . '/cache/', 'baseUri' => '/dbProject/', ] ]);
步骤3: 执行迁移数据库“demodb”中包含的表的命令。目前,它包括一个表“user”:
步骤4: 迁移的数据库文件存放在“app”文件夹下的migrations目录中:
这样,表就成功迁移了。
迁移文件的结构
迁移的文件有一个独特的类,它继承了Phalcon\Mvc\Model\Migration类。Phalcon中的Migration类包括up()和down()方法,up()方法用于执行迁移,而down方法则是回滚操作。
Users.php
<?php use Phalcon\Db\Column; use Phalcon\Db\Index; use Phalcon\Db\Reference; use Phalcon\Mvc\Model\Migration; /** * Class UserMigration_100 */ class UserMigration_100 extends Migration { /** * Define the table structure * * @return void */ public function morph() { $this->morphTable('user', [ 'columns' => [ new Column( 'Id', [ 'type' => Column::TYPE_INTEGER, 'notNull' => true, 'autoIncrement' => true, 'size' => 11, 'first' => true ] ), new Column( 'username', [ 'type' => Column::TYPE_VARCHAR, 'notNull' => true, 'size' => 40, 'after' => 'Id' ] ), new Column( 'email', [ 'type' => Column::TYPE_VARCHAR, 'notNull' => true, 'size' => 40, 'after' => 'username' ] ), new Column( 'password', [ 'type' => Column::TYPE_VARCHAR, 'notNull' => true, 'size' => 10, 'after' => 'email' ] ) ], 'indexes' => [new Index('PRIMARY', ['Id'], 'PRIMARY') ], 'options' => [ 'TABLE_TYPE' => 'BASE TABLE', 'AUTO_INCREMENT' => '3', 'ENGINE' => 'InnoDB', 'TABLE_COLLATION' => 'latin1_swedish_ci' ], ] ); } /** * Run the migrations * * @return void */ public function up() { } /** * Reverse the migrations * * @return void */ public function down() { } }
在上面的例子中,UserMigration_100类包含有四个部分的关联数组,分别是:
Columns: 包括一组表格列;
Indexes: 包括一组表索引;
References: 包括所有的参照完整性约束(外键);
Options: 带有一组表创建选项的数组。
如上例所示,数据库的 1.0.0 版已成功迁移,Phalcon 可能包含并运行多个迁移过程,具体取决于数据库内容的保存方式。