问题
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 tablebooks
add constraintbooks_doba_foreign
foreign key (doba
) referencesdruh_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