Search code examples
laravelmodel-view-controllermigrationlaravel-migrations

why foreign key not get setted in laravel migrations


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 App\Models;

use App\Models\Question;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Exam extends Model
{
    use HasFactory;

    protected $fillable = [
        //
    ];

    public function questions(){
        return $this->hasMany(Question::class);
    }
}

question model

<?php

namespace App\Models;

use App\Models\Exam;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Question extends Model
{
    use HasFactory;

    function exam(){
        return $this->belongsTo(Exam::class);
    }
}

exam migration

<?php

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

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 Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

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


Solution

  • Try to add the constrained method when you define the foreign key in question's migration, change:

    $table->foreignId('exam_id');
    

    to:

    $table->foreignId('exam_id')->constrained();