My question is not regarding hook_schema but regarding hook_update_N: I need to add a foreign key to an existent table in drupal 7.

I was looking Here but it does not seem to exist one explicitly for foreign keys.

Q: How can I create a foreign key in an existent table? Which call should I do?


The underlying DBMS all support this, but Drupal7 Core doesn't really care about Foreign Keys (FKs). Views will notice them and use them abit within joins.

Drupal 7 only supports FK in documentation: http://www.interworks.com/blogs/jkhalaj/2012/04/12/drupal-7-usage-foreign-keys-schema-api-and-current-default-fk-erd

But, if you know this and understand this, then you can still use this foreign key defintion to create the FKs in a module.install file specific to your DBMS.

I use MySQL typically -- and I have done this for a foreign database my settings.php is aware of within a module.install file:

function _idremotedb_add_foreign_keys() {
  $schema = _idremotedb_schema_definition();
  foreach ($schema as $table => $table_schema) {
    if (isset($table_schema['foreign keys'])) {
      foreach ($table_schema['foreign keys'] as $fk_name => $fk_details) {
        $src_col = $fk_details['columns'][0];
        $dest_col = $fk_details['columns'][1];
        $dest_table = $fk_details['table'];
        // Create the FK using your DBMS convention. Change this as necessary
        // or add a lookup to the database handler driver type (mysql, postgres, whatever) ...
          ALTER TABLE $table ADD CONSTRAINT $fk_name
          FOREIGN KEY ($src_col) REFERENCES $dest_table($dest_col);
        drupal_set_message(t('...added foreign key: !fk', array('!fk' => $fk_name)));
  // This index added for either mail-list or login.
  #db_add_index('students', 'uniqueidnumber', 'campusuniqueidnumber');
| improve this answer | |
  • Seems you're right, and learned that it also does not exist in the schema core, being like a big "TO-DO". Drupal sucks - and I'm forced to use it. The (part I used from the) code you gave me works :). – Luis Masuelli Aug 25 '14 at 22:29
  • @LuisMasuelli No problem. I hope it works -- it's live on a site i have :). And it looks like D8 will have some support for creating FKs in contrib modules but not used explicitly in Core: drupal.org/node/2254131 – tenken Aug 25 '14 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.