Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Migration: auto increment key when it is not primary

I'm trying to create a table with Laravel migrations but I'm having some trouble. I just need to create a table with a primary pair ('id' and 'revision'), being 'id' an auto increment. I can do it in MySQL, but I can't manage to do it with Laravel Migrations since increments() also set the field as primary. So far I have this:

Schema::create('bibliographies', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('revision');
        ...
        $table->timestamps();
        $table->softDeletes();
        $table->primary(array('id', 'revision'));
    });

Note: changing increments() method is not an option since it is Laravel core.

Thank you for your help in advance.

like image 902
CarlosMaia Avatar asked Nov 01 '14 21:11

CarlosMaia


Video Answer


2 Answers

 $table->unsignedInteger('id')->change();//will remove the auto increment
 $table->dropPrimary('id');//will remove primary constrain
 $table->unsignedInteger('revision') //add revision column
 $table->primary( array( 'id', 'revision' ) );//make them both primary
 $table->increments('id')->change()//add the auto increment constrain back  
like image 20
Abhishek Deshpande Avatar answered Sep 29 '22 19:09

Abhishek Deshpande


Just drop the primary key before you re-add it:

$table->dropPrimary( 'id' );
$table->primary( array( 'id', 'revision' ) );
like image 107
Joe Avatar answered Sep 29 '22 18:09

Joe