Skip to content

Instantly share code, notes, and snippets.

@deepakaryan1988
Forked from sumanthkumarc/hook_update_N.php
Created July 28, 2020 08:27
Show Gist options
  • Save deepakaryan1988/82b5945ae82a50e563619a0e122bfc3c to your computer and use it in GitHub Desktop.
Save deepakaryan1988/82b5945ae82a50e563619a0e122bfc3c to your computer and use it in GitHub Desktop.
Drupal 8: Create a new table in database using hook_update_N()
<?php
/**
*The numbers are normally composed of three parts:
* - 1 or 2 digits for Drupal core compatibility (Drupal 8, 9, 10, etc.). This
* convention must be followed.
* - 1 digit for your module's major release version; for example, for 8.x-1.*
* use 1, for 8.x-2.* use 2, for Core 8.0.x use 0, and for Core 8.1.x use 1.
* This convention is optional but suggested for clarity.
* - 2 digits for sequential counting, starting with 01. Note that the x000
* number can never be used: the lowest update number that will be recognized
* and run for major version x is x001.
* Examples:
* - node_update_8001(): The first update for the Drupal 8.0.x version of the
* Drupal Core node module.
* - mymodule_update_8101(): The first update for your custom or contributed
* module's 8.x-1.x versions.
* - mymodule_update_8201(): The first update for the 8.x-2.x versions.
*/
/**
* Adds new table "my_table".
*/
function MY_MODULE_update_8001() {
$database = \Drupal::database();
$schema = $database->schema();
$table_name = 'my_table';
$table_schema = [
'fields' => [
'sid' => [
'type' => 'serial',
'size' => 'big',
'not null' => TRUE,
],
'nid' => [
'type' => 'int',
'not null' => TRUE,
],
'action' => [
'type' => 'varchar',
'not null' => TRUE,
'length' => 25,
],
'uids' => [
'type' => 'blob',
'not null' => TRUE,
],
],
'primary key' => ['sid'],
];
$schema->createTable($table_name, $table_schema);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment