How to handle (create table, alter ...) database schemas on drupal 8 ?
Get Database Schema
$schema = \Drupal\Core\Database\Database::getConnection()->schema();
Create a table.
$spec = array(
'description' => 'New table description',
'fields' => array(
'id' => array(
'type' => 'serial',
'not null' => TRUE,
),
'name' => array(
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
'default' => '',
),
'value' => array(
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
'default' => '',
),
),
'primary key' => array('id'),
);
$schema->createTable('the_table_name', $spec);
Drop / Delete a field.
$schema = Database::getConnection()->schema();
$schema->dropField('the_table_name', 'field_to_drop');
Add a field to a table.
$spec = array(
'type' => 'varchar',
'length' => '255',
'not null' => TRUE,
'default' => '0',
);
$schema->addField('the_table_name', 'field_to_add', $spec);
Examples
Delete a table field from hook_update_N()
/**
* Update 8001, Delete Field 'field_to_delete' from table 'the_test_table'.
*/
function mymodule_update_8001(&$sandbox) {
$schema = \Drupal\Core\Database\Database::getConnection()->schema();
$schema->dropField('the_test_table', 'field_to_delete');
return ('The field field_to_delete has been dropped from the_test_table');
}
More :
https://api.drupal.org/api/drupal/includes!database!schema.inc/group/schemaapi/7.x
Comments