drupalforeign-keysdrupal-7drupal-modulesdrupal-schema

Foreign keys in Drupal 7 schema trouble


I have a trouble with Drupal 7 schema for module. There are 4 tables but for sample 2 will be enough:

function mymodule_schema() {
$schema['series'] = array(
    'fields' => array(
        'id' => array(
            'type' => 'serial',
            'unsigned' => true,
            'not null' => true,
        ),
        'name' => array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => true,
        ),
    ),
    'unique keys' => array(
        'name' => array('name'),
    ),
    'primary key' => array('id'),
);

$schema['sermon'] = array(
    'fields' => array(
        'id' => array(
            'type' => 'serial',
            'unsigned' => true,
            'not null' => true,
        ),
        'title' => array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => true,
        ),
        'series_id' => array(
            'type' => 'int',
        ),
    ),
    'foreign keys' => array(
        'series_id' => array(
            'table' => 'series',
            'columns' => array('series_id' => 'id'),
        ),
    ),
    'primary key' => array('id'),
);
return $schema;
}

This code create tables but not foreign keys. Example for implementation I get from Drupal.org: http://drupal.org/node/146939

Drupal version is 7.0-beta 3 ..As idea: maybe, it isn't implemented yet, I don't see it in node table (documentation example point to code from it's installer).

Thank for your help.


Solution

  • According to this post, just a few months ago, the hook_schema function does not implement the creation of foreign keys. It can, however, reference existing ones.

    Perhaps a work-around would be to run the foreign-key-adding SQL in hook_init (or one of the other API methods). Sorry, there doesn't seem to be a better resolution to this right now.