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!!! :(
check if in the user table the id is unsigned and is a primary key or if you made $table->inscrements('id') in it ..
– Vagner do Carmo
Yeah, it’s like
unsigned
and was created as$table->increments('id')
– Ewerton Melo