Drupal 8 - dodanie tabeli do bazy danych w module
Kolejny artykuł z cyklu tworzenia modułów do Drupala. Tym razem pokażę jak we własnym module dodać tabelę do bazy danych. Należy utworzyć plik my_module.install w katalogu głównym modułu. W celu utworzenia własnej tabeli potrzebujesz przynajmniej metody hook_schema() w pliku my_module.install. również używamy poniżej hook_install(), która jest wywoływana po hook_schema(), aby dodać kilka przykładowych rekordów do naszej tabeli mymodule_managers.
<?php
/**
* hook_schema()
*/
function my_module_schema() {
$schema['mymodule_managers'] = array(
'description' => 'Store managers',
'fields' => array(
'pid' => array(
'type' => 'serial',
'not null' => TRUE,
'description' => 'Primary Key: Unique manager ID.',
),
'uid' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => "Creator user's {users}.uid",
),
'name' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
'description' => 'Name of the manager.',
),
'age' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'size' => 'tiny',
'description' => 'The age of the manager in years.',
),
),
'primary key' => array('pid'),
'indexes' => array(
'name' => array('name'),
'age' => array('age'),
),
);
return $schema;
}
/**
* hook_install()
*/
function my_module_install() {
$values = [
[
'name' => 'Paul',
'age' => 30,
'uid' => 1,
],
[
'name' => 'Jan',
'age' => 40,
'uid' => 1,
],
];
$database = \Drupal::database();
$query = $database->insert('mymodule_managers')->fields(['name', 'age', 'uid']);
foreach ($values as $m) {
$query->values($m);
}
$query->execute();
}
Tabela jest tworzona w momencie instalacji modułu. Natomiast podczas deinstalacji
jest usuwana.
