这种迁移有什么问题



您好,我现在正在练习Laravel,我正在进行一些迁移,但是当我尝试运行迁移时,我遇到了以下错误。

[Illuminate\Database\QueryException] SQLSTATE[23000]:完整性约束冲突:1452 无法添加或更新子行:外键约束失败 ( sample .#sql-1d0c_20f、约束products_product_type_id_foreign外键(product_type_id(引用 S product_types ( id ( 在删除级联上( (SQL: 更改表products添加约束products_product_type_id_foreig n外键 ( product_type_id ( 引用 product_types ( id ( 在删除级联上(

[PDOException] SQLSTATE[23000]:完整性约束冲突:1452 无法添加或更新子行:外键约束失败 ( sample .#sql-1d0c_20f、约束products_product_type_id_foreign外键(product_type_id(引用 S product_types ( id ( 在删除级联上(

这是我product_types迁移代码

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('product_types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('product_type')->unique();
        $table->tinyInteger('status')->nullable(false); //1 for active 2 for inactive
        $table->timestamps('created_at');
    });

}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('product_types');
}

产品表中添加 FK 约束

 /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
     /**
     * Drop column type in products table
     */
    Schema::table('products', function (Blueprint $table) {
        $table->dropColumn('type');
    });
    /**
     * Create column product_type in products table
     */
    Schema::table('products', function (Blueprint $table) {
        $table->integer('product_type_id')->unsigned()->after('price');
        $table->foreign('product_type_id')->references('id')->on('product_types')->onDelete('cascade');
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    /**
     * Drop column product_type_id in products table
     */
    Schema::table('products', function (Blueprint $table) {
        $table->dropForeign('product_type_id');
        $table->dropColumn('product_type_id');
    });
    /**
     * Re-create column type in products table
     */
    Schema::table('products', function (Blueprint $table) {
        $table->string('type')->after('price');
    });
}

尝试更改迁移顺序,确保product_types在产品表之前。

最新更新