Creating Foreign Keys by Migration - Laravel

Asked

Viewed 5,625 times

2

I’m having trouble when I try to create foreign keys by Migration in Laravel.

Watch 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 execute the command:

php artisan migrate

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!!! :(

  • 1

    check if in the user table the id is unsigned and is a primary key or if you made $table->inscrements('id') in it ..

  • Yeah, it’s like unsigned and was created as $table->increments('id')

1 answer

2

The mistake was mine... :

When I created Migration inverti the fields in Ferences() 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 those who were willing to help!!!

Browser other questions tagged

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