使用 CakePHP 3.x 構建第一個 Hello World 應用程式(資料庫表遷移。第 2 部分)
你可以輕鬆地為你的資料庫提供表格,或者如果你願意,可以使用它們。如果你希望這樣做,你應該學習如何為所需的資料庫編寫 Migrations
。
遷移檔案必須位於 config/Migrations
資料夾中。檔名可以採用下列格式:
YYYYMMDDHHIISS_(Create|Alter|Delete)AdministratorsTable.php
(1-9){1,}_(Create|Alter|Delete)AdministratorsTable.php
<?php
use Migrations\AbstractMigration;
use Cake\Log\Log;
/**
* Class AdministratorsTableMigration
*/
class AdministratorsTableMigration extends AbstractMigration
{
/**
* @var string
*/
private $_tableName;
/**
* @var string
*/
private $_tablePrefix;
public function init()
{
$this->_tableName = '"Administrators"';
$this->_tablePrefix = 'administrators';
}
public function up()
{
Log::info("Trying to create {$this->_tableName} table");
$administratorsTable = $this->table($this->_tablePrefix);
if ($administratorsTable->exists()) {
return Log::warning("Table {$this->_tableName} already exists");
}
$administratorsTable
->addPrimaryKey('id')
->addColumn('username', 'char', [
'length' => 25,
'null' => false
])
->addColumn('password', 'char', [
'length' => 255,
'null' => false
])
->addColumn('email', 'char', [
'length' => 50,
'null' => false
])
->addColumn('first_name', 'char', [
'length' => 50,
'null' => false
])
->addColumn('last_name', 'char', [
'length' => 50,
'null' => false
])
->addColumn('avatar', 'char', [
'length' => 255,
'default' => '/img/no-avatar.png'
])
->addColumn('active', 'boolean', [
'default' => 0
])
->addTimestamps()
->create();
return Log::notice("Table {$this->_tableName} has been created");
}
public function down()
{
if ($this->table($this->_tablePrefix)->exists()) {
$this->table($this->_tablePrefix)->drop();
return Log::info("Table {$this->_tableName} has been dropped");
}
return Log::warning("Table {$this->_tableName} does not exists");
}
}
如果要執行遷移,則需要執行下一個命令:
bin/cake migrations migrate
建立表(-s)。
如果要回滾:
bin/cake migrations rollback
- 將恢復上次遷移,其中存在 drop()
功能
bin/cake migrations (-t|--target) all
- 將恢復所有遷移,其中存在 drop()
功能