外键约束形式不正确(在InnoDB中)

huangapple go评论65阅读模式
英文:

Foreign key constraint is incorrectly formed (with inno db)

问题

当运行以下代码时:

Schema::create('files', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->id();
  $table->string('path');
  $table->timestamps();
});
Schema::create('file_users', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->id();
  $table->integer('file_id');
  $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
  $table->mediumInteger('user_id');
  $table->timestamps();
});

我收到以下错误信息:

SQLSTATE[HY000]: General error: 1005 无法创建表 atomes.file_users(错误号:150 "外键约束形式不正确")(SQL: alter table file_users add constraint file_users_file_id_foreign foreign key (file_id) references files (id) on delete cascade)

互联网上的答案都没有帮助到我。

我尝试将表类型更改为 myISAM,但对我没有起作用。

英文:

When running:

Schema::create('files', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->id();
  $table->string('path');
  $table->timestamps();
});
Schema::create('file_users', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->id();
  $table->integer('file_id');
  $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
  $table->mediumInteger('user_id');
  $table->timestamps();
});

I'm getting error:

>SQLSTATE[HY000]: General error: 1005 Can't create table atomes.file_users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table file_users add constraint file_users_file_id_foreign foreign key (file_id) references files (id) on delete cascade)

None of the internet answers helped me.

I tried changing the table types to myISAM but that didn't work for me.

答案1

得分: 0

尝试这样做

    Schema::create('file_users', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->id();
        $table->foreignId('file_id')->nullable(true)->constrained('files')->onUpdate('cascade')->onDelete('cascade');
        $table->foreignId('user_id')->constrained('users');
        $table->timestamps();
    });

<details>
<summary>英文:</summary>

try this

    Schema::create(&#39;file_users&#39;, function (Blueprint $table) {
        $table-&gt;engine = &#39;InnoDB&#39;;
        $table-&gt;id();
        $table-&gt;foreignId(&#39;file_id&#39;)-&gt;nullable(true)-&gt;constrained(&#39;files&#39;)-&gt;onUpdate(&#39;cascade&#39;)-&gt;onDelete(&#39;cascade&#39;);
        $table-&gt;foreignId(&#39;user_id&#39;)-&gt;constrained(&#39;users&#39;);
        $table-&gt;timestamps();
    });

</details>



huangapple
  • 本文由 发表于 2023年2月13日 23:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定