0

Hello I am practicing Laravel now and I'm doing some migration but when I try to run my migration I got this following errors.

[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( sample.#sql-1d0c_20f, CONSTRAINT products_product_type_id_foreign FOREIGN KEY (product_type_id) REFERENCE S product_types (id) ON DELETE CASCADE) (SQL: alter table products add constraint products_product_type_id_foreig n foreign key (product_type_id) references product_types (id) on delete cascade)

[PDOException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( sample.#sql-1d0c_20f, CONSTRAINT products_product_type_id_foreign FOREIGN KEY (product_type_id) REFERENCE S product_types (id) ON DELETE CASCADE)

this is my my product_types migration code

/**
 * 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');

}

Adding FK constrain in product table

 /**
 * 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');
    });
}
Novice
  • 77
  • 2
  • 11
  • The order of executing those migration files is important...product_types needs to be before product table – lewis4u Feb 02 '18 at 09:29
  • is there no other way? I created the producty_types table 1st before I added new column for product_type_id in product table. – Novice Feb 07 '18 at 06:33

1 Answers1

0

Try changing the migrations order, being sure product_types is before product table.