Skip to main content

How to create a custom database table with Database Schema in Drupal 8

Recently i had to build a custom simple table in a drupal 8 installation that would be used as an api feed bridge between drupal 8 and a custom api feed service. This is the code i used for the custom table with an extra tip for the date field since there is no date type by default in drupal.

function api_data_install(){
    $spec = [
        'description' => 'Scanning Actions Raw Data',
        'fields' => [
          'id' => [
            'type' => 'serial',
            'not null' => TRUE,
          ],
          'nid' => [
            'type' => 'int',
            'not null' => TRUE,
            'default' => '0',
            'unsigned' => TRUE,
          ],
          'mac_address' => [
            'type' => 'varchar',
            'not null' => TRUE,
            'length' => 20,
            'default' => '',
          ],
          'rssi' => [
            'type' => 'int',
            'not null' => TRUE,
          ],
          'scanner_id' => [
            'type' => 'int',
            'not null' => TRUE,
          ],
          'start_date' => [
            'type' => 'varchar',
            'mysql_type' => 'datetime',
            'not null' => TRUE,
          ],
          'current_date' => [
            'type' => 'varchar',
            'mysql_type' => 'datetime',
            'not null' => TRUE,
          ],
          'created_date' => [
            'type' => 'varchar',
            'mysql_type' => 'datetime',
            'not null' => TRUE,
          ],
        ],
        'primary key' => ['id'],
      ];
     $schema = Database::getConnection()->schema();
     $schema->createTable('scanning_raw_data', $spec);

    }

You can add this to your hook_install in your custom module file like this: my_custom_module.module. And for uninstalling the table with the custom module.

function api_data_uninstall(){
    $table = 'scanning_raw_data';
    $schema = Database::getConnection()->schema();
    $schema->dropTable($table);
}