当我使用以下语法删除行时:
$user->delete();
有没有办法附加某种回调,以便它可以例如自动执行此操作:
$this->photo()->delete();
最好在模型类内。
我相信这是一个完美的用例雄辩事件 https://laravel.com/docs/10.x/eloquent#events-using-closures。您可以使用“删除”事件来进行清理:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function photos()
{
return $this->has_many('Photo');
}
// this is a recommended way to declare event handlers
protected static function booted () {
static::deleting(function(User $user) { // before delete() method call this
$user->photos()->delete();
// do the rest of the cleanup...
});
}
}
您可能还应该将整个事物放入事务中,以确保引用完整性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)