dimanche 19 avril 2020

Laravel / lumen incompatible foreign key constraint

I have two tables, one is profiles. Below is how the migration file for profiles looks like

    public function up()
    {
    Schema::create(
        'profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique()->notNullable();
            $table->string('phone');
            $table->integer('category')->unsigned();
            $table->string('password');
            $table->timestamps();

            $table->foreign('category')
                ->references('id')
                ->on('categories')
                ->onDelete('cascade');
        });
    }

profiles has a foreign key id on its local category field. The migration file for categories table looks like so

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->integer('id')->unsigned();
        $table->primary('id');
        $table->string('name');
        $table->string('abbrv');
        $table->timestamps();
    });
}

The problem is when i try to add data to the profiles table, i get below error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (authdb.profiles, CONSTRAINTprofiles_category_foreignFOREIGN KEY (category) REFERENCEScategories(id) ON DELETE CASCADE) (SQL: insert intoprofiles(name,email,phone,category,password,updated_at,created_at) values (Salim, jon.doe@gmail.com, 2557000000, 2, $2y$10$OgpgD61e9Ihob4oE1LoRZuMkMY/1u6yLzxPKvs36TAQtQzSfqShMS, 2020-04-19 13:34:20, 2020-04- 19 13:34:20))

How do i define the foreign key constraint so it doesn't throw constraint errors ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire