Creating Foreign Keys by Migration - Laravel

2

I'm having trouble when I try to create foreign keys for Migration in Laravel.

Look at my Migration !!!

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateEmpresaUsuarioTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('empresa_usuario', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->integer('id_usuario')->unsigned();
        $table->foreign('id_usuario')->references('usuario')->on('id');
        $table->integer('id_empresa')->unsigned();
        $table->foreign('id_empresa')->references('empresa')->on('id');
        $table->timestamps();
        $table->softDeletes();
    });
}


/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('empresa_usuario');
}

}

I run the command:

php artisan migrate

It gives the following error:

[Illuminate\Database\QueryException]                                         
SQLSTATE[HY000]: General error: 1005 Can't create table 'catalogrep.#sql-40  
b_65' (errno: 150) (SQL: alter table 'empresa_usuario' add constraint empre  
sa_usuario_id_usuario_foreign foreign key ('id_usuario') references 'id' ('  
usuario'))

The funny thing is that the table is created, but the relationship is not !!! :

    
asked by anonymous 22.06.2014 / 02:37

1 answer

2

The error was my ...: s

When I created the migration I inverted the fields in references () and on ()

Where is:

$table->foreign('id_usuario')->references('usuario')->on('id');

Should be:

$table->foreign('id_usuario')->references('id')->on('usuario');

My fault, thanks to whoever was willing to help !!!

    
22.06.2014 / 03:01