我正在尝试覆盖模型上的delete方法。
在我的用户模型中,我有这样的代码:
public function delete()
{
if ( ! is_null($this->remote_id)) {
$this->location_id = null;
$this->save();
} else {
parent::delete();
}
}基本上,如果remote_id为null,此方法将删除记录。如果不为null,则通过将location_id设置为null来断开用户与该位置的连接。
当我执行$user->delete()时,这个方法会被调用,并且工作得很好。
但是,当我删除类似$location-> users ()->delete()这样的位置的所有用户时,该方法不会被调用。我做错了什么吗?
发布于 2015-07-19 04:07:39
如果您希望使用模型方法(或触发模型事件),则需要遍历所有用户并逐个删除它们,例如:
$location->users->map(function($user) {
$user->delete();
});如果你有很多用户,这样的操作可能非常耗时,所以我宁愿更新所有相关的模型,而不是获取它们并对每个模型调用():
$location->users()->update(['location_id' => null]);发布于 2015-07-19 04:14:32
你可以试试这个:
// In App/Location.php
public static function boot()
{
parent::boot();
static::deleting(function($location) {
foreach($location->users as $user) {
if( ! is_null($user->remote_id) ) {
$user->location_id = null;
$user->save();
}
else {
$user->delete();
}
}
});
}当您删除任何User模型时,这将根据location_id状态(如果location_id为null)删除所有Location模型,但如果location_id不是null,则user->location_id的值将更新为null。
https://stackoverflow.com/questions/31494097
复制相似问题