Drupal hook schema doesn’t support foreign keys out of the box, but you can easily add them (as long as your table is created as INNODB)

Table Types

If you want to see which tables are INNODB run:

SELECT TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'database name'

Foreign keys - gotchas

1. Table types must be INNODB

2. Table fields must be of a similar type (e.g. INT to INT, its even specific about the sign so if its unsigned then it must be unsigned to unsigned).

The Code

Subject to your table being INNODB (if it’s not you can change the table engine but I’ll leave you to check that out) and the fields being of similar type then just add an update hook, e.g.

/**
* Implements hook_update_N();
*/
function abexperiments_update_6004() {
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'pgsql':
      break;
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("
        ALTER TABLE abexperiments_log
          ADD CONSTRAINT i_experiment_id
          FOREIGN KEY (experiment_id)
          REFERENCES abexperiments (id)
          ON DELETE NO ACTION
          ON UPDATE NO ACTION");
  }
  return $ret;
}

 

Tags: