Laravel Eloquent删除关系表

时间:2015-03-12 10:18:41

标签: php laravel laravel-4 migration eloquent

如何在laravel 4.2上删除关系表的关系?例如,我有一个名为category的表,它与子类别相关。因此,类别id与子类别作为外键相关,并在我的迁移中映射为级联删除。现在子类别表与对象表有关系。因此,子类别id与作为外键的对象相关,并在删除时映射为级联。现在,当我删除类别时,子类别被删除,这很好。但是由于子类别被删除了,甚至对象也应该被删除了吗?但事实并非如此。怎么解决这个?以下是我的代码。

类别模型

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

子类别模型

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 个答案:

答案 0 :(得分:0)

您需要直接在每个模型上调用->delete()来触发关联的模型事件

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