This is my first Laravel project and I’m having a hard time defining a table with a many-to-many relationship.
I want to create a table which will ‘link’ each teacher from a table with one or more domains they are interested in. Each domain can be linked to multiple teachers.
I approached the idea this way:
<?php use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class teacherAndTheirDomain extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('teacherAndTheirDomain', function (Blueprint $table) { $table->unsignedInteger('teacher_id'); $table->unsignedInteger('domain_id'); $table->foreign('teacher_id') ->references('id')->on('teachers') ->onDelete('cascade'); $table->foreign('domain_id') ->references('id')->on('domains') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('teacherAndTheirDomain'); } }
but I get “Can’t create table, foreign key constraint is incorrectly formed”.
Can anybody explain to me what I’m doing wrong, please, and why am I getting this error?
Thanks 🙂
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Foreign key constraints must be of the same type as the referencing table. As explained on ‘Conditions and Restrictions’ on https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
Since Laravel 7, the default is set to $table->bigIncrements('id');
instead of $table->increments('id');
. Hence, the foreign key should be of the same type:
$table->unsignedBigInteger('teacher_id'); $table->unsignedBigInteger('domain_id');
The rest of the migration file stays the same.
ps: you don’t need to use big integers as the table id
type. In most circumstances, falling back on the old $table->increments('id');
will be just fine. Once you made a choice, try to be consistent in all other migrations to avoid future conflicts in your application.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0