0

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');
    }
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95

2 Answers2

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');
mrhn
  • 17,961
  • 4
  • 27
  • 46
1

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');
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291