首页 > 解决方案 > Laravel 5.8 迁移中的外键未知(MEDIUMINT?)问题

问题描述

我在向表中添加 MEDIUMINT 外键约束时遇到问题。我知道它有效,在BASE TABLEorganization_id也引用了 MEDIUMINT。FOREIGN TABLE中的第一个外键有效,但第二个无效。

我肯定知道的事情:

我尝试过的事情:

基表

        Schema::create('customers', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedMediumInteger('organization_id');
            $table->unsignedMediumInteger('customer_id');
            $table->string('customer_domain');
            $table->timestamps();

            // Foreign Keys
            $table->foreign('organization_id')->references('id')->on('organizations');
        });

外国表

        Schema::create('numberblocks', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('group_id')->index();
            $table->unsignedMediumInteger('customer_id');
            $table->unsignedMediumInteger('order_id');
            $table->string('number', 15);
            $table->timestamps();

            // Foreign Keys
            $table->foreign('group_id')->references('id')->on('groups');
            $table->foreign('customer_id')->references('customer_id')->on('customers');
        });

我尝试过的一切都以同样的错误告终:

SQLSTATE[HY000]: General error: 1005 Can't create table 'db'.'#sql-1a78_2a6'
(errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'numberblocks' add constraint 'numberblocks_customer_id_foreign'
foreign key ('customer_id') references 'customers' ('customer_id'))```

我的问题:有没有其他人知道让这个工作的方法?

标签: phpmysqllaravel

解决方案


是的,正如错误所说

一般错误:1822 无法添加外键约束。引用表'customers'中的约束'numberblocks_customer_id_foreign'缺少索引")

所以尝试添加

$table->index(['customer_id']);

在客户迁移中并将解决问题

如果不是请在下面评论


推荐阅读