How to add a foreign key with Migration?

0

I'm now learning to use Migration of Laravel . I was able to understand the understanding well, but I 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 foreign key in the nivel_id field that references niveis.id .

How can I do this in Laravel ?

    
asked by anonymous 29.04.2016 / 14:29

1 answer

3

Simple like this:

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);
});

link

    
30.04.2016 / 10:30