Laravel 5.8迁移中外键的未知(MEDIUMINT?)问题

时间:2019-06-15 20:14:06

标签: php mysql laravel

我在向表添加MEDIUMINT外键约束时遇到麻烦。 我知道它有效,在 基本表 中,organization_id还引用了MEDIUMINT。 FOREIGN TABLE 中的第一个外键有效,但是第二个无效。

我肯定知道的事情:

  • 父表和子表都具有unsignedMediumInteger;
  • 外国专栏已创建;和
  • 在父表和外部列创建之后添加键。

我尝试过的事情:

  • $table->unsignedMediumInteger('customer_id');更改为$table->mediumInteger('customer_id')->unsigned();
  • 在相同的迁移中将外键从Schema::create('numberblocks')分离到Schema::table('numberblocks')
  • 将数据类型更改为INT,SMALLINT;
  • 在子表中将名称从customer_id更改为c_id;和
  • 将外键设置为其自己的迁移。

基本表

        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'))```

我的问题: 还有其他人知道使此工作正常进行的方法吗?

1 个答案:

答案 0 :(得分:0)

是的,正如错误所述

  

一般错误:1822无法添加外键约束。失踪   引用中约束“ numberblocks_customer_id_foreign”的索引   nced表'customers'“)

所以尝试添加

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

在客户迁移中,将解决此问题

如果不是下面的友善评论

相关问题