迁移时外键出错 Laravel 5.8
Error foreign key when doing migration Laravel 5.8
我在 Laravel 5.8
上出错
我在外键约束方面遇到错误。这是我的架构..
public function up()
{
Schema::create('subcategories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
我认为您应该尝试将 Categories
Table 放在上面,将 sub categories
放在下面。因为当您 运行 此命令时,它会首先尝试创建子类别,这需要尚不存在的类别 ID。
引用的键必须具有相似的数据types.Please检查您的table外键列的数据类型。整数类型的大小和符号必须相同。
您正在 subcategories
之后创建 categories
table。创建时间 subcategory
table,没有 table 调用 categories
。所以它会抛出一个错误。
要处理这个问题,您可以做两件事
在 subcategories
table 之前创建 categories
table。 (master-slave table / parent-child table)
为外键更新创建一个单独的迁移文件。创建一个新文件并在外键下方添加如下
$table->foreign('category_id')->references('id')->on('categories');
试试这个
Schema::create('subcategories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
我在 Laravel 5.8
上出错我在外键约束方面遇到错误。这是我的架构..
public function up()
{
Schema::create('subcategories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
我认为您应该尝试将 Categories
Table 放在上面,将 sub categories
放在下面。因为当您 运行 此命令时,它会首先尝试创建子类别,这需要尚不存在的类别 ID。
引用的键必须具有相似的数据types.Please检查您的table外键列的数据类型。整数类型的大小和符号必须相同。
您正在 subcategories
之后创建 categories
table。创建时间 subcategory
table,没有 table 调用 categories
。所以它会抛出一个错误。
要处理这个问题,您可以做两件事
在
subcategories
table 之前创建categories
table。 (master-slave table / parent-child table)为外键更新创建一个单独的迁移文件。创建一个新文件并在外键下方添加如下
$table->foreign('category_id')->references('id')->on('categories');
试试这个
Schema::create('subcategories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});