You can easily create
tables for Your database or drop
them if You want.
If You wish to do that, You should learn how to write Migrations
for desired database.
Migrations files must be located in config/Migrations
folder. File names can be in next formats:
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");
}
}
If You want to run migration, You need to run next command:
bin/cake migrations migrate
to create table(-s).
If You want to rollback:
bin/cake migrations rollback
- will revert last migration, where drop()
function exists
bin/cake migrations (-t|--target) all
- will revert all migrations, where drop()
function exists