如何删除 Laravel 中可能为空的关系?
How to delete a Relationship in Laravel that could be null?
当用户决定停用他的帐户时,我也会删除属于该用户的所有其他 table。
在App\User中:
protected static function boot()
{
parent::boot();
static::deleting(function ($user) {
$user->privacy->delete();
$user->info->delete();
$user->comments->each->delete();
//If connected
$user->instagram->delete(); //my Problem
});
}
public function instagram(){
return $this->hasOne(SocialInstagramAccount::class);
}
如果可以为空,有没有什么好的方法可以使用现有的关系来删除模型?
使用上面的代码我得到:"Call to a member function delete() on null" 当用户没有使用 Instagram 登录时。显然 null->delete() 不起作用。
使用这个:
$user->instagram()->delete();
$user->comments()->delete();
当用户决定停用他的帐户时,我也会删除属于该用户的所有其他 table。
在App\User中:
protected static function boot()
{
parent::boot();
static::deleting(function ($user) {
$user->privacy->delete();
$user->info->delete();
$user->comments->each->delete();
//If connected
$user->instagram->delete(); //my Problem
});
}
public function instagram(){
return $this->hasOne(SocialInstagramAccount::class);
}
如果可以为空,有没有什么好的方法可以使用现有的关系来删除模型?
使用上面的代码我得到:"Call to a member function delete() on null" 当用户没有使用 Instagram 登录时。显然 null->delete() 不起作用。
使用这个:
$user->instagram()->delete();
$user->comments()->delete();