I made an exam-question relationship, every exam has less than 200 questions, but when I run migrations, I go to the PHPMyAdmin and I don’t find the foreign key set, it’s only a bigint(20) unsigned
column and not linked to the exams table.
exam model
<?php
namespace AppModels;
use AppModelsQuestion;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentFactoriesHasFactory;
class Exam extends Model
{
use HasFactory;
protected $fillable = [
//
];
public function questions(){
return $this->hasMany(Question::class);
}
}
question model
<?php
namespace AppModels;
use AppModelsExam;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentFactoriesHasFactory;
class Question extends Model
{
use HasFactory;
function exam(){
return $this->belongsTo(Exam::class);
}
}
exam migration
<?php
use IlluminateSupportCarbon;
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateExamsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('exams', function (Blueprint $table) {
$table->id();
$table->string('examHash')->unique();
//..
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('exams');
}
}
questions migrations
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->foreignId('exam_id')->constrained();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('questions');
}
}
I’ve tried to:
Use this
$table->foreign('exam_id')->references('id')->on('exams');
but
Key column ‘exam_id’ doesn’t exist in table
EDIT:
it can be caused because my engine is not InnoDB, regularly I change the engine to InnoDB to create foreign keys
3
Answers
the problem as I've mentioned in the question is in the engine. so I wrote
in both of question and exam tables...
The method
foreignId
will only create anUNSIGNED BIGINT
and not a foreign key constraint. To also create a constraint you need to callconstrained()
afterward.Try this:
You can also find more information in the documentation.
Try to add the constrained method when you define the foreign key in question’s migration, change:
to: