Friday, March 17, 2017

Integrity Constraint Violation when seeding database in Laravel 5

I'm trying to seed my database in Laravel 5. The migration is successful but I get an error when trying to seed:

[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ict302`.`psas`, CONSTRAINT `psas_psa_user_
id_foreign` FOREIGN KEY (`psa_user_id`) REFERENCES `users` (`id`))

Below are my migrations:

User table:

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    Schema::dropIfExists('users');
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}

PSA Table:

public function up()
    {
        Schema::create('psas', function (Blueprint $table) {
            $table->increments('psa_id');
            $table->timestamps();
            $table->string('psa_email',50);
            $table->unique('psa_email');
            $table->string('psa_name', 30);
            $table->integer('psa_user_id')->unsigned()->onDelete('cascade');
        });

        Schema::table('psas', function (Blueprint $table)
        {
            $table->foreign('psa_user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        Schema::dropIfExists('psas');
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }

Database Seeder class:

public function run()
    {
        //Model::unguard();
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        $this->call(AccessTableSeeder::class);
        $this->call(HistoryTypeTableSeeder::class);

        $this->call(UserTableSeeder::class);
        $this->call(PsaTableSeeder::class);
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        //Model::reguard();
    }

What am I doing wrong and how can I fix it?



via Gautam Nath

Advertisement