Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Handle database schemas on Drupal 8

By editor , 22 November, 2016
Question

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

Tags

  • Drupal 8
  • Code
  • Database
Database Basic Examples (Select, Merge, Insert ...)
Update a node / Entity programmatically in Drupal 8

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer