Laravel 5.2迁移:无法添加char数据类型的外键 [英] Laravel 5.2 Migration: Cannot add foreign key of char data type

查看:72
本文介绍了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.

[Illuminate \ Database \ QueryException] SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:更改表 levels add约束 levels_sample_type_id_foreign 外键( sample_type_id )引用 sample_types ( id ))

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table levels add constraint levels_sample_type_id_foreign foreign key (sample_type_id) references sample_types (id))

[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数据类型的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆