小编典典

自动删除Laravel(Eloquent ORM)中的相关行

php

当我使用以下语法删除一行时:

$user->delete();

有没有一种方法可以附加各种回调,以便例如自动执行此操作:

$this->photo()->delete();

最好在模型类内部。


阅读 337

收藏
2020-05-26

共1个答案

小编典典

我相信这是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...
        });
    }
}

您可能还应该将整个内容放入事务中,以确保引用完整性。

2020-05-26