当我使用以下语法删除一行时:
$user->delete();
有没有一种方法可以附加各种回调,以便例如自动执行此操作:
$this->photo()->delete();
最好在模型类内部。
我相信这是Eloquent事件的完美。您可以使用“删除”事件进行清理:
class User extends Eloquent { public function photos() { return $this->has_many('Photo'); } // this is a recommended way to declare event handlers public static function boot() { parent::boot(); static::deleting(function($user) { // before delete() method call this $user->photos()->delete(); // do the rest of the cleanup... }); } }
您可能还应该将整个内容放入事务中,以确保引用完整性。