我不知道为什么它仍然不起作用并显示以下内容:
Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规错误:1005无法创建表
db_rocnikovka
。books
(错误号:150“外键约束格式不正确”)(SQL:alter tablebooks
添加约束books_doba_foreign
外键(doba
)参考druh_knihies
(id_druhu
))在C:\ xampp \ htdocs \ Rocnikovka \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection.php:665
异常跟踪:1 PDOException::(“ SQLSTATE [HY000]:常规错误:1005无法创建>表
db_rocnikovka
。books
(错误号:150”外键约束格式不正确“)”)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
);
}
第一张桌子
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');
}
}
第二张表
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');
}
}
您的外键必须与其引用的键具有相同的类型。因此,需要将第二个表外键doba
更改为此,因为您在第一个表主键中使用了BigIncrements()
。
$table->unsignedBigInteger('doba');
这里的问题是id_druhu
中的druh_knihies
被定义为bigIncrements
,并且您将doba
创建为unsignedInteger
,并且在使用外键类型时应该完全相同。因此,在这种情况下,代替
$table->unsignedInteger('doba');
您应该使用
$table->unsignedBigInteger('doba');