简体   繁体   中英

Laravel Eloquent delete relation table

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();
    });

}
}

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(); 
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM