How to add a Foreign key with Migration?

Asked

Viewed 4,611 times

1

I’m learning now how to use the Migrationof Laravel. I managed to understand well the functioning, but still do not know how to add a foreign_key

I have the following Migration:

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

       $bp->unsignedInteger('nivel_id');
       $bp->string('nome');
       $bp->string('username');

       $bp->string('password', 455);
  });

I need to create a key Foreign in the field nivel_id which refers to niveis.id.

How can I do that in Laravel?

1 answer

6

Simple as that:

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

   $bp->integer('nivel_id')->unsigned();
   $bp->foreign('nivel_id')->references('id')->on('niveis');

   $bp->string('nome');
   $bp->string('username');
   $bp->string('password', 455);
});

https://laravel.com/docs/5.2/migrations#Foreign-key-constraints

Browser other questions tagged

You are not signed in. Login or sign up in order to post.