外键 laravel 迁移

foreign key laravel migration

这是我的 students 迁移,我想在其中包含名为 subject_id:

的外键
public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('student_code');
        $table->string('national_code');
        $table->integer('subject_id')->unsigned();
        $table->foreign('subject_id')
            ->references('id')->on('subjects');
        $table->timestamps();
    });
}

这是我的 subjects 迁移:

public function up()
{
    Schema::create('subjects', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->timestamps();
    });
}

我的问题很简单,我在文档中搜索,除了我的迁移代码外什么也没找到。我很迷惑。 无论如何首先我 运行 subjects 迁移脚本然后 students 但我得到 st运行ge 错误:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table students add constraint students_subject_id_foreign foreign key (subject_id) references subjects (id))

问题出在您定义顺序的字段上。您必须先添加所有字段,然后再添加外键。

试试下面的代码:-

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('student_code');
        $table->string('national_code');
        $table->integer('subject_id')->unsigned();
        $table->timestamps();

        $table->foreign('subject_id')
            ->references('id')->on('subjects');
    });
}

因此,您的 subjects table id 具有 BIG INT 数据类型,subject_id 应该具有相同的数据类型。

改用$table->unsignedBigInteger('subject_id');

Reference:

a foreign key column must have the same data type + the same length + the same scale as the corresponding referenced column

看起来您的问题在 subject_id 定义中。 本地和外键必须是同一类型,在我们的例子中:

$table->unsignedBigInteger('subject_id');

https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html:

Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.