我在laravel类别的教程下面用户:
Laravel categories with dynamic deep paths
我使用下面的代码相同的教程进行迁移:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug');
$table->integer('parent_id')->unsigned()->default(0);
$table->timestamps();
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
});
}
但我有以下错误:
SQLSTATE[HY000]: General error: 1005 Can't create table 'xxx'.'#sql-453_147' (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'categories' add constraint 'categories_parent_id_foreign' foreign key ('parent_id') references 'categories' ('id') on delete cascade on update cascade)
感谢帮助
在Laravel中创建新表时。将生成迁移,如:
$table->bigIncrements('id');
而不是(在较旧的Laravel版本中):
$table->increments('id');
使用bigIncrements时,外键需要bigInteger而不是整数。所以你的代码看起来像这样:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug');
$table->bigInteger('parent_id')->unsigned()->default(0);
$table->timestamps();
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
});
}
问题是由于列类型的不同。因此,与使用bigIncrements
的教程不同,这意味着ID的大整数,并使用parent_id
的默认整数。尝试将id
更改为:
$table->increments('id');
或者你的parent_id
:
$table->bigInteger('parent_id')->unsigned()->default(0);