I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_ent_id_foreign` foreign key (`ent_id`) references `id_ent` (`entreprises`))
My migration code for 'Entreprises'
public function up()
{
Schema::create('entreprises', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id_ent');
$table->string('name');
$table->string('numSiret', 14)->unique();
$table->integer('nbr_couvert')->length(10);
$table->timestamps();
});
}
My migration code for 'Users'
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id_user');
$table->string('log');
$table->string('name', 45);
$table->string('firstName', 45);
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->string('num_phone', 20);
$table->datetime('created_at');
$table->unsignedInteger('ent_id');
$table->integer('agenda_id')->nullable();
$table->tinyInteger('droitUser')->nullable();
$table->boolean('validateMail');
$table->string('key', 255);
});
Schema::table('users', function ($table) {
$table->foreign('ent_id')
->references('entreprises') //here
->on('id_ent'); //and here
});
I change the order of the migrations and the table 'entreprises' are create before the 'users' table.
I tried every solutions from here and here and they are nothing to change.
Any suggestions someone ?
Editing for solution
Shame on me... I just do a stupid mistake when I reference the table I wanted to reference... Everything is fine now... Sorry