-2

I want to delete the product_id in the inventories table after deleting a specific group.

Table Structure:

product_groups
id | grp_name

products
id | prod_name | price | group_id

inventories
id | product_id | in_stock

Code:

public function ProductGroups_destroy($id)
{
    $product_group = ProductGroup::find($id);

    $product_group->delete();

    $product_group->product()->delete();

    $product_group->product->inventory()->delete();

    Session::flash('success', 'Product group deleted');
    return redirect()->back();
}

Models

Product Model, ProductGroup Model

Inventory Model

3gth
  • 550
  • 5
  • 23

1 Answers1

1

1) You can use this in your Inventory Migration :

$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

Source : https://laravel.com/docs/5.5/migrations#foreign-key-constraints

2) You can overwrite the delete method :

class Product extends Model {

    protected $table = 'products';

    public function inventory(){
        return $this->hasMany('App\Inventory', 'product_id');
    }

    public function delete()    
    {
        DB::transaction(function() 
        {
            $this->inventory()->delete();
            parent::delete();
        });
    }

}
  • I have the following error on my migration "errno: 150 "Foreign key constraint is incorrectly formed" (SQL: alter table 'inventories' add constraint 'inventories_product_id_foreign' foreign key<'product_id'> references 'products' <'id'> on delete cascade) General error: 1005 cant create table. errno: 150 "Foreign key constraint is incorrectly formed" – ElementsOfLife Oct 06 '17 at 01:55
  • Try to write new migration with removal of foreign key first and then reassigning foreign key. Please check this link : https://stackoverflow.com/questions/26820788/add-on-delete-cascade-to-existing-column-in-laravel – Waleed Khan Oct 06 '17 at 06:30
  • Syntax error or access violation: 1091 Cant drop 'product_id_foreign': check that column/key exists.. These are my tables, products -> |id|prod_name|group_id|. inventories -> |id|product_id|instock| – ElementsOfLife Oct 06 '17 at 14:41
  • I got it working.. but after deleting the group.. i got this error (Method inventory does not exist.). Controller Code: public function ProductGroups_destroy($id) { $product_group = ProductGroup::find($id); $product_group->delete(); $product_group->product()->delete(); $product_group->product->inventory()->delete(); Session::flash('success', 'Product group deleted'); return redirect()->back(); } – ElementsOfLife Oct 06 '17 at 15:05
  • It worked.. using $product_group->product()->delete(); Thanks! – ElementsOfLife Oct 06 '17 at 15:25