自动删除 Laravel 中的相关行(Eloquent ORM) [英] Automatically deleting related rows in Laravel (Eloquent ORM)
本文介绍了自动删除 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();
最好在模型类内部.
推荐答案
我相信这是 Eloquent 事件的完美用例 (http://laravel.com/docs/eloquent#model-events).您可以使用删除"事件进行清理:
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屋!
查看全文