IntroductionLast updated: 04/10/2020
data definition or data description language DDL is a syntax for creating and modifying database objects such as tables, indexes, and users.
PHPtricks-ORM Builder
Class allows you to creating and modifying database tables only.
PHPtricks-ORM allows you to generate DDL
Classes via Command-line,
this doc page to describe Builder
Class methods.
Create Table :
use PHPtricks\Orm\Builder;
class CreateTable extends Builder
{
protected $_table = 'table_name';
public function run()
{
return $this->schema($schemaAsArray)->create();
}
}
EX :
use PHPtricks\Orm\Builder;
class CreateTable extends Builder
{
protected $_table = 'students';
public function run()
{
return $this->schema([
'id' => 'increments',
'name' => 'string:255 | not_null',
'number' => 'int|unsigned',
])->create();
}
}
the SQL Statement for this :
CREATE TABLE students (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(255) NOT NULL,
number INT UNSIGNED
)
PLEAS NOTE:
'id' => 'increments'
mean the id column well be integer
,primary key
, auto increment
, not null
, and unsigned
.
ADD Constraints
'number' => 'int|my_constraint|other_constraint|more_constraint';
SO the first one is a column type and others well be Constraints
Default Value
to set default value type :
'number' => 'int|unsigned|default:222';
'name' => 'int|unsigned|default:hello-this-a-default-value';
// note : the character (-) replaced with white space
Full Example :
use PHPtricks\Orm\Builder;
class CreateUsersTable extends Builder
{
protected $_table = 'users';
private $_schema = [
'id' => 'increments',
'username' => 'string:100|not_null',
'full_name' => 'string:255|default:no-name',
'joined' => 'timestamp',
'user_email' => 'string:100|not_null',
];
public function run()
{
return $this->schema($this->_schema)->create();
}
}
ADD Column :
$userTable = new CreateUsersTable();
$userTable->alterSchema(['add', 'column_name', 'type'])->alter();
or inside class :
EX:
use PHPtricks\Orm\Builder;
class CreateUsersTable extends Builder
{
protected $_table = 'users';
public function addColumn($colName, $colType)
{
$this->alterSchema(['add', $colName, $colType])->alter();
}
}
RENAME Column :
$userTable = new CreateUsersTable();
$userTable->alterSchema(['rename', 'last_login', 'last_session'])->alter();
EDIT Column type:
$userTable = new CreateUsersTable();
$userTable->alterSchema(['modify', 'full_name', 'text'])->alter();
DROP Column :
$userTable = new CreateUsersTable();
$userTable->alterSchema(['drop', 'full_name'])->alter();
DROP Table :
$userTable = new CreateUsersTable();
$userTable->drop();