Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set auto increment into non primary key?

How would I set a database auto increment field that is not a primary key on the creation method?

The only way is using a raw query?

DB::statement('ALTER TABLE table CHANGE field field INT(10)AUTO_INCREMENT');

like image 375
Luiz Avatar asked Mar 21 '17 14:03

Luiz


People also ask

Can I auto increment a non primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.

Is auto increment always primary key?

A Primary Key just needs to be a unique value that identifies its entry from other entries, and not null. Save this answer. Show activity on this post. Primary key should be unique but not necessarily need to be auto_increment.

How do I reset my auto increment primary key?

In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name. The name of the table whose AUTO_INCREMENT column you wish to reset.

How do I add an auto increment to an existing table?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.


1 Answers

It is not implemented to do so. However, I found this over at the Laravel Forums:

Schema::table('table', function(Blueprint $t) {
    // Add the Auto-Increment column
    $t->increments("some_column");

    // Remove the primary key
    $t->dropPrimary("table_some_column_primary");

    // Set the actual primary key
    $t->primary(array("id"));
});

This is not tested but should work. I am not sure about how Laravel calls their primary keys, maybe you have to check that first and adapt the dropPrimary() line in order to make it work.

like image 195
Niklas S. Avatar answered Sep 27 '22 23:09

Niklas S.