Table operations (create, update, drop table and table schema)
Porte can manage the database through the "PorteTable" objects. Available operations include table creation and drop. Moreover, the table structure can be automatically updated to reflect the defined record classes.
Accessing a "table" object
Table objects are available from connections and records objects.
-
From a connection
The method getTable from the connection object accept a record instance or a record type string. A handy shortcut is made available throug a property which take the plural form of a record type. -
From a record
A property "table" is made available to each record.
Method "create"
Create a new table, does not check if table exists unless the "drop" option is provided.
- param Array (optional) Array of options
- return boolean True on success
- throws PorteException
Available option includes:
- drop: Drop table if exists, optional
Using the "create" method:
$user = new User();
// Create a new table, but an error will be thrown if table already exists
$user->table->create();
// Create a new table, drop the existing table if it exists
$user->table->create(array('drop'));
Method "exists"
Check if table exists.
- return boolean True if table exists, false otherwise
Using the "exists" method:
$user = new User();
if($user->table->exists()){
// table exists
}else{
// table does not exist
}
Method "drop"
Delete a table if it exists.
- return boolean True on success
- throws PorteException
Using the "exists" method:
$user = new User();
$user->table->drop();
The "update" method
Create the table schema for the model definitions. Handle all sort of relationships, if an existing table exists, new fields will be created but does not yet handle the migration of existing fields.
Note, field present in the database table and not referenced in the object will removed (it is planned to have this configurable).
- params array Array of options (optional)
- return boolean True on success
- throws: PorteException
Available options includes:
- drop: Drop table if exists, optional
Using the "update" method:
$user = new User();
$user->table->update();
The "fields" method
List all the fields present in the table. The return value is an array with the field names as keys.
Tip: To get an array of all the fields:
$user = new User();
$fields = array_keys( $user->table->fields() );