【问题标题】:General error: 1005 Can't create table (errno: 150 "Foreign key constraint is incorrectly formed") [duplicate]一般错误:1005 无法创建表(errno:150“外键约束格式不正确”)[重复]
【发布时间】:2022-01-25 20:14:21
【问题描述】:

我在 Laravel 8 中有一个数据库迁移,如下所示:

class CreateArticlesTable extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->text('body');
            $table->string('imageUrl');
            $table->string('tags');
            $table->integer('viewCount')->default(0);
            $table->integer('commentCount')->default(0);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

但是每当我想运行它时,我都会收到此错误:

一般错误:1005 无法创建表elearning.articles(errno:150“外键约束格式不正确”)

我不知道这里到底出了什么问题,所以如果你知道如何解决这个问题,请告诉我...

【问题讨论】:

  • @rickdenhaan 不,它不能回答我的问题,因为该问题的解决方案不能应用于这个问题。
  • 那么您能否编辑您的问题并解释您尝试了哪些解决方案以及为什么它们不适合您的情况?我链接的问题有 27 个答案以及针对此问题的各种可能的解决方案,从检查以确保表是 InnoDB 表到确保以正确的顺序创建表并且您链接在一起的两列是相同的类型和属性。

标签: php mysql laravel laravel-8 laravel-migrations


【解决方案1】:

而不是使用:

$table->integer('user_id')->unsigned();

用途:

$table->unsignedBigInteger();

Laravel 使用 unsignedBigInteger 是 20 位,unsignedInteger 只需要 11 位

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

【讨论】:

  • 如何才能找到“user_id”列而不提?
  • 你能解释一下吗
  • 对不起.... $table->unsignedBigInteger('user_id');
【解决方案2】:

用户表和文章表的引擎是否相同,都是InnoDB? MyISAM 不支持外键。 如果是,是在用户表之后创建文章表吗?如果答案是肯定的,那么: 两个字段是否完全相同?我认为您的用户 ID 是自动递增的,如果是,则添加未签名的外键:

 $table->foreign('user_id')->unsigned()->references('id')->on('users')->onDelete('cascade');

【讨论】:

    【解决方案3】:

    在 Laravel 8 上试试这个

    $table->id();
     $table->unsignedBigInteger('user_id')->unsigned();
     $table->foreign('user_id')->on('users')->references('id')->onDelete('cascade');
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 2020-11-27
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2020-12-02
      • 2020-07-05
      • 2020-12-19
      相关资源
      最近更新 更多