How to fix foreign key error when running migration

放肆的年华 提交于 2020-01-22 02:31:08

问题


I don't know why it's still don't work and show this:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table db_rocnikovka.books (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table books add constraint books_doba_foreign foreign key (doba) references druh_knihies (id_druhu))

at C:\xampp\htdocs\Rocnikovka\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665

Exception trace: 1 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create > table db_rocnikovka.books (errno: 150 "Foreign key constraint is incorrectly formed")") C:\xampp\htdocs\Rocnikovka\vendor\laravel\framework\src\Illuminate\Database\Connection.php:459

2 PDOStatement::execute()

  C:\xampp\htdocs\Rocnikovka\vendor\laravel\framework\src\Illuminate\Database\Connection.php:459
 catch (Exception $e) {
    throw new QueryException(
       $query, $this->prepareBindings($bindings), $e
    );
 }

First table

class CreateDruhKnihiesTable extends Migration
{
    public function up()
    {
        Schema::create('druh_knihies', function (Blueprint $table) {
            $table->bigIncrements('id_druhu');
            $table->string('nazev');
            $table->timestamps();
        });
    }

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

Second table

class CreateBooksTable extends Migration
{
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->bigIncrements('id_book');
            $table->string('nazev');
            $table->string('autor');
            $table->string('druh');
            $table->unsignedInteger('doba');
            $table->foreign('doba')->references('id_druhu')->on('druh_knihies');
            $table->integer('pocet_stranek');
            $table->timestamps();
        });
    }

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

回答1:


You foreign key needs to have the same type as the key it references. Therefor the second table foreign key doba needs to be change to this, becuase you use BigIncrements() in the first table primary key.

$table->unsignedBigInteger('doba');



回答2:


The problem here is that id_druhu in druh_knihies is defined as bigIncrements and you create doba as unsignedInteger and when using foreign key type should be exactly same. So in this case instead of

$table->unsignedInteger('doba');

you should use

$table->unsignedBigInteger('doba');


来源:https://stackoverflow.com/questions/59555437/how-to-fix-foreign-key-error-when-running-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!