【问题标题】:Laravel 5.2 Migration: Cannot add foreign key of char data typeLaravel 5.2 迁移:无法添加 char 数据类型的外键
【发布时间】:2016-11-21 15:50:09
【问题描述】:

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

[Illuminate\Database\QueryException] SQLSTATE[HY000]:一般错误: 1215 无法添加外键约束(SQL:alter table levels add 约束levels_sample_type_id_foreign外键 (sample_type_id) 引用sample_types (id))

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

这是levels表的迁移文件内容

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表如下

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

【问题讨论】:

  • sample_types.id 列是什么类型?
  • 我相当肯定两者必须属于同一类型。所以sample_type_id 不能为空。
  • sample_types 是在levels 之前创建的?
  • @miken32,你是对的。表级别是在 sample_types 之前创建的。我现在可以毫无问题地生成外键。谢谢你。您能否将此评论添加为答案?

标签: php mysql laravel laravel-migrations


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 2016-06-06
    • 2016-06-24
    • 2019-03-24
    • 2017-03-27
    • 2015-03-14
    • 2021-08-30
    • 2016-11-11
    • 2017-03-03
    相关资源
    最近更新 更多