Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Composite key indexes in migrations

Composite indexes are a subject I'm not fully experienced in, I wasn't sure if I was doing it right? Or if Laravel is parsing my code correctly when migrating. Does this look correct?

Schema::create('friends', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('requester_id')->unsigned();
    $table->integer('requestee_id')->unsigned();
    $table->timestamps();

    $table->foreign('requester_id')->references('id')->on('users');
    $table->foreign('requestee_id')->references('id')->on('users');

    $table->unique(['requester_id', 'requestee_id'], 'composite_index');
});

Here is what Sequel Pro shows:

http://i.imgur.com/5A4LZH3.png

like image 907
Stuart Hannig Avatar asked Dec 12 '14 00:12

Stuart Hannig


2 Answers

What you have there is correct.


Note: you don't have to specify the index's name. Laravel will automatically generate a name for you based on the columns being indexed.

like image 81
Joseph Silber Avatar answered Sep 21 '22 18:09

Joseph Silber


Here's my example: creating unique external_id for every user user_id:

    Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');

        $table->string('external_id')->nullable();
        $table->unique(['external_id', 'user_id']); // <<---------

        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        // ...
    });
like image 24
Mahmoud Zalt Avatar answered Sep 21 '22 18:09

Mahmoud Zalt