Spencer Rohan
Spencer Rohan

Reputation: 1939

Laravel 5 Deleting a one-to-many relationship

I have two tables: - Products - Themes

Products belong to a Theme - Themes has many Products.

I want to delete a theme and remove it's association with any Products. In a perfect world deleting a theme would reset the related Products' theme_id to NULL. In my Products table I have tried ->onDelete('cascade') but this deletes both the Theme and corresponding Products. If I do not implement ->onDelete('cascade') I get this error:

QLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (acme.products, CONSTRAINT products_theme_id_foreign FOREIGN KEY (theme_id) REFERENCES themes (id) ON DELETE CASCADE) (SQL: update products set theme_id = , updated_at = 2015-12-28 20:20:05 where id = 1)

Any suggestions would be super helpful. Thank You!

Upvotes: 2

Views: 1330

Answers (1)

Sergio Guillen Mantilla
Sergio Guillen Mantilla

Reputation: 1468

You have to define your product foreign key onDelete to set null and also the foreign key field as nullable

  Schema::create('products', function(Blueprint $t) {
        ...
        $t->integer('theme_id')->unsigned()->nullable();
        ...

        $t->foreign('theme_id')->references('id')->on('themes')
            ->onDelete('set null');
    });

Upvotes: 2

Related Questions