You are here

public function Table::addPrimaryKey in Data 8

Add a primary key to table.

Throws

DataException

1 call to Table::addPrimaryKey()
Table::changePrimaryKey in src/Table.php
Change the primary keys of a table.

File

src/Table.php, line 392

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 addPrimaryKey($fields) {
  $schema = $this->table_schema;
  foreach ($fields as $field) {
    if ($schema['fields'][$field]['type'] == 'text') {
      throw new DataException(t('A text field cannot be made a primary key.'));
    }
  }
  try {
    \Drupal::database()
      ->schema()
      ->addPrimaryKey($this->name, $fields);
  } catch (DatabaseSchemaObjectExistsException $e) {
    throw new DataException(t('Error creating primary key.'));
  }
  $schema['primary key'] = $fields;
  $this
    ->update(array(
    'table_schema' => $schema,
  ));
  drupal_get_schema($this->name, TRUE);
}