Automatically deleting related rows in Laravel (Eloquent ORM)

后端 未结 13 1754
半阙折子戏
半阙折子戏 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:42

    It is better if you override the delete method for this. That way, you can incorporate DB transactions within the delete method itself. If you use the event way, you will have to cover your call of delete method with a DB transaction every time you call it.

    In your User model.

    public function delete()
    {
        \DB::beginTransaction();
    
         $this
            ->photo()
            ->delete()
        ;
    
        $result = parent::delete();
    
        \DB::commit();
    
        return $result;
    }
    

提交回复
热议问题