5

I have created an update that adds a fields to an existing database table. I would like to add that field to the list of primary keys already defined. How do I do this? Do I need to execute the following code?

db_drop_primary_key('table_name');
db_change_field('table_name', 'field_name', 'field_name',
array('type' => 'int', 'not null' => TRUE, 'unsigned' => TRUE),
array('primary key' => array(...list of field names...)));

I essentially recreate either an existing field or the new one I just added. Is there a simpler method where I can just add the field name to primary key list?

1 Answer 1

14

Very close. In a hook_update_N:

// Drop all primary keys.
db_drop_primary_key('table_name');
// Add primary keys.
db_add_primary_key('table_name', array('field_a', 'field_b'...);

See db_drop_primary_key and db_add_primary_key for details and links to usage.

2
  • 2
    Thanks for the answer, I am little new here... forgive me if its silly question but do I have to use hook_update to do this ..? @jonpeck
    – Hitesh
    Commented Feb 2, 2015 at 12:04
  • 1
    Yes if you have already defined the primary key in the hook_schema().
    – user5013
    Commented Feb 2, 2015 at 22:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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