2
votes

How to delete relation table's relations on laravel 4.2? For example, I have a table called category which is related to subcategory. So, category id is related to subcategory as foreign key and mapped for cascade delete in my migrations. Now subcategory table has relations with objects table. So subcategory id is related to objects as foreign key and mapped for cascade on delete. Now when I delete category, subcategory is getting deleted which is fine. But since subcategory is getting deleted, even objects too should get deleted right? But it is not. How to solve this?. Below is my code.

Category Model

 use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Category extends Eloquent{

use SoftDeletingTrait;

protected $dates = ['deleted_at'];

protected $table = "categories";

public function subcategory(){
    return $this->hasMany('Subcategory', 'category_id');
}

public static function boot()
{
    parent::boot();

    Category::deleting(function($category) {
        $category->subcategory()->delete();
    });
}
}

SubCategory model

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Subcategory extends Eloquent{

use SoftDeletingTrait;

protected $dates = ['deleted_at'];

public $timestamps = false;

protected $table = "subcategories";

public function parent(){
    return $this->belongsTo('Category', 'category_id');
}

public function objects(){
    return $this->hasMany('Object', 'subcategory_id');
}

public static function boot()
{
    parent::boot();

    Subcategory::deleting(function($subcategory) {
        $subcategory->objects()->delete();
    });

}
}
1
So when you call $someCategory->delete(), both categories and subcategories tables are affected by removing the category and their associated subcategories, right? In this case I think you have what you need, and the remaining objects are references to records that no longer exist in the database, so you can simply do $someCategory = NULL after deleting and that should destroy the outdated references in your PHP code.Josué
Nothing will get removed. I do only soft delete. $category->delete() will soft delete subcategory. But since subcategory is now soft deleted then even its related tables(objects) should get soft deleted right?Saravanan Sampathkumar

1 Answers

0
votes

You need to call ->delete() on each model directly to trigger associated model events

Category::deleting(function($category) {
    foreach($category->subcategory as $subcategory){
        $subcategory->delete(); 
    }
});