You are here

public function Table::addUniqueKey in Data 8

Add a unique key to a field.

Throws

DataException

File

src/Table.php, line 328

Class

Table
Manages data access and manipulation for a single data table. Use data_create_table() or data_get_table() to instantiate an object from this class.

Namespace

Drupal\data

Code

public function addUniqueKey($field) {
  $schema = $this->table_schema;
  if ($schema['fields'][$field]) {
    $index = data_get_index_definition($field, $schema['fields'][$field]);
    try {
      $success = \Drupal::database()
        ->schema()
        ->addUniqueKey($this->name, $field, $index);
    } catch (DatabaseSchemaObjectExistsException $e) {
      throw new DataException(t('Error adding unique key.'));
    }
    if ($success) {
      $schema['unique keys'][$field] = array(
        $field,
      );
      $this
        ->update(array(
        'table_schema' => $schema,
      ));
      drupal_get_schema($this->name, TRUE);
      return;
    }
  }
}