首页 > 解决方案 > 如何解决这个错误 SQLSTATE[HY000]: General error: 1005 Can't create table

问题描述

运行迁移时出现此错误

SQLSTATE[HY000]:一般错误:1005 无法创建表tms-app#sql-1e64_2b(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table projectsadd constraint projects_cout_id_foreignforeign key ( cout_id) references couts( id) on update cascade)

这是项目表:

  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();

        });

标签: laravel

解决方案


有时会发生此错误,当我们定义外键并且您应该使用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();
});

注意:在表格中couts&statuses将 id 字段更改$table->increments('id');$table->bigIncrements('id');


推荐阅读