【问题标题】:how to solve this erorr SQLSTATE[HY000]: General error: 1005 Can't create table如何解决这个错误 SQLSTATE[HY000]: General error: 1005 Can't create table
【发布时间】:2021-07-06 16:07:25
【问题描述】:

运行迁移时出现此错误

SQLSTATE[HY000]: 一般错误: 1005 Can't create table tms-app.#sql-1e64_2b (errno: 150 "外键约束格式不正确") (SQL: alter table projects add constraint projects_cout_id_foreign更新级联时外键 (cout_id) 引用 couts (id)

这是项目表:

  Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('libelle');
            $table->string('libelle_long');
            $table->string('direction');
            $table->integer('cout_id')->unsigned();
            
            $table->foreign('cout_id')
                ->references('id')->on('couts')
                ->onUpdate('cascade');
            $table->foreign('status')
                ->referenecs('id')->on('statuses')
                ->onUpdate('cascade')
                ->onDelete('cascade');
            $table->timestamps();

        });

【问题讨论】:

  • 欢迎来到 SO。请添加couts表的迁移
  • 迁移couts表之前需要先迁移projects

标签: laravel


【解决方案1】:

有时会发生此错误,当我们定义外键时,您应该使用bigInteger('') 或使用unsignedBigInteger('')

使用下面的代码:

Schema::create('projects', function (Blueprint $table) {
    $table->increments('id');
    $table->string('libelle');
    $table->string('libelle_long');
    $table->string('direction');

    $table->bigInteger('cout_id')->unsigned();
    $table->bigInteger('status')->unsigned();
    $table->foreign('cout_id')->references('id')->on('couts')->onDelete('cascade');
    $table->foreign('status')->references('id')->on('statuses')->onDelete('cascade');
    $table->timestamps();
});

注意:在表 coutsstatuses 中将 id 字段 $table->increments('id'); 更改为 $table->bigIncrements('id');

【讨论】:

  • 有时不行,这是5.8及以上版本,你也需要将增量更改为bigIncrements
  • 确保您的用户表迁移发生在 q&a 表之前,因为 q&a 迁移文件引用了 users 表,因此它必须存在。通常,laravel 会根据创建日期执行迁移文件,因此最好考虑先执行用户表,然后再执行 q&a。
  • 我有这个错误`(SQL:更改表projects添加约束projects_status_foreign外键(status)引用statuses()在更新级联上删除级联)`
  • 我已经编辑了答案,你现在可以看到了。
【解决方案2】:

这个错误应该是我下面提到的下面的错误配置引起的,请确保所有这些都正确配置

1:Laravel 迁移外键应分配为 bigInteger 或 unsignedBigInteger 例子: $table->unsignedBigInteger('user_id'); 要么 $table->bigInteger('user_id')->unsigned();

对于分配外键属性,您应该这样做 $table->foriegn('user_id')->reference('id')->on('users'); // 如果你需要更多的属性,你可以链接到这一行

2:确保迁移文件的顺序正确形成,因为 Laravel 将根据时间戳迁移表,例如如果需要用户表中的外键,则首先需要创建用户表,然后子表是用户表的时间戳应该比孩子大(甚至 1 秒)

【讨论】:

    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 2011-01-29
    • 2021-10-15
    • 1970-01-01
    • 2021-08-31
    • 2021-04-24
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多