本文介绍了Laravel 5.2迁移:无法添加char数据类型的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建 char数据类型的可空外键.当我运行migration命令时.我收到以下错误.我不确定我在哪里做错了.

I am trying to create a nullable foreign key of char data type. When I run the migrate command. I get the following error. I am not sure, where I am doing wrong.

[PDOException] SQLSTATE [HY000]:常规错误:1215无法添加外部关键约束

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

这是级别表的迁移文件内容

Here is the migration file contents for levels table

public function up()
{
    Schema::create('levels', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->char('id', 36)->unique();
        $table->string('description')->nullable();
        $table->char('sample_type_id', 36)->nullable();
        $table->integer('order');
        $table->timestamps();
        $table->primary('id');
        $table->foreign('sample_type_id')->references('id')->on('sample_types');
    });
}

以及sample_types表如下

and for the sample_types table are as follows

public function up()
{
    Schema::create('sample_types', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->char('id', 36)->unique();
        $table->string('name');
        $table->timestamps();
        $table->primary('id');
    });
}

推荐答案

如果所引用的表尚不存在,则外键语句将失败.在 levels 迁移文件中引用表之前,请确保已创建 sample_types 表.

The foreign key statement will fail if the table being referred to does not exist yet. Ensure that you create the sample_types table before referring to it in the levels migration file.

这篇关于Laravel 5.2迁移:无法添加char数据类型的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 01:37