Automatically deleting related rows in Laravel (Eloquent ORM)

后端 未结 13 1912
半阙折子戏
半阙折子戏 2020-11-22 17:03

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 auto

13条回答
  •  一整个雨季
    2020-11-22 17:47

    Note: This answer was written for Laravel 3. Thus might or might not works well in more recent version of Laravel.

    You can delete all related photos before actually deleting the user.

    has_many('Photo');
        }
    
        public function delete()
        {
            // delete all related photos 
            $this->photos()->delete();
            // as suggested by Dirk in comment,
            // it's an uglier alternative, but faster
            // Photo::where("user_id", $this->id)->delete()
    
            // delete the user
            return parent::delete();
        }
    }
    

    Hope it helps.

提交回复
热议问题