为什么没有在 laravel 迁移中设置外键

why foreign key not get setted in laravel migrations

我做了一个考题关系,每次考试都不到200道题,但是我运行迁移的时候,我去PHPMyAdmin里面找不到外键集,只有一个bigint(20) unsigned 列且未链接到考试 table。

考试模型

<?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);
    }
}

提问模型

<?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);
    }
}

考试迁移

<?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');
    }
}

问题迁移

<?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');
    }
}

我试过:

使用这个

$table->foreign('exam_id')->references('id')->on('exams');

但是

Key column 'exam_id' doesn't exist in table

编辑: 这可能是因为我的引擎不是InnoDB,我经常将引擎换成InnoDB来创建外键

方法 foreignId 只会创建一个 UNSIGNED BIGINT 而不是外键约束。要同时创建约束,您需要在之后调用 constrained()
试试这个:

Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('exam_id')->constrained();
            $table->timestamps();
        });

您还可以在 documentation 中找到更多信息。

尝试在定义问题迁移的外键时添加约束方法,更改:

$table->foreignId('exam_id');

至:

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

我在问题中提到的问题出在引擎中。所以我写了

$table->engine = 'InnoDB';

在问题表和考试表中...