自动删除Laravel(Eloquent ORM)中的相关行 [英] Automatically deleting related rows in Laravel (Eloquent ORM)

查看:99
本文介绍了自动删除Laravel(Eloquent ORM)中的相关行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I delete a row using this syntax:

$user->delete();

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

Is there a way to attach a callback of sorts, so that it would e.g. do this automatically:

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

最好在模型类内部.

推荐答案

我认为这是处理口才事件的完美用例(

I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the "deleting" event to do the cleanup:

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

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

You should probably also put the whole thing inside a transaction, to ensure the referential integrity..

这篇关于自动删除Laravel(Eloquent ORM)中的相关行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆