删除所有与 static::deleting 模型的关系

时间:2021-02-13 15:15:13

标签: laravel eloquent

我已经尝试使用事件处理程序来删除关系,但它不能用于删除关系的关系。事件 hasMany Person 和 Person hasMany File

class Event
    public static function boot() {
        parent::boot();
        static::deleting(function($model) { // before delete() method call this
            $model->person()->delete();
        });
    }
}

class Person
    public static function boot() {
        parent::boot();
        static::deleting(function($model) { // before delete() method call this
            $model->files()->delete();
        });
    }
}

所以当我删除事件时,它可以删除人,但不会删除文件行。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您应该一一调用它以在每个模型实例上调用引导方法。所以,获取实例,然后将它们一一删除。

#items: array:2 [▼
    0 => {#277 ▼
      +"type": "Milk"
      +"serial": 3
    }
    1 => {#278 ▼
      +"type": "Milk"
      +"serial": 2
    }
]
class Event
    public static function boot() {
        parent::boot();
        static::deleting(function($model) { // before delete() method call this
            foreach($model->person as $person){
              $person->delete();
            }
        });
    }
}
相关问题