Automatically deleting related rows in Laravel (Eloquent ORM)

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

    Or you can do this if you wanted, just another option:

    try {
        DB::connection()->pdo->beginTransaction();
    
        $photos = Photo::where('user_id', '=', $user_id)->delete(); // Delete all photos for user
        $user = Geofence::where('id', '=', $user_id)->delete(); // Delete users
    
        DB::connection()->pdo->commit();
    
    }catch(\Laravel\Database\Exception $e) {
        DB::connection()->pdo->rollBack();
        Log::exception($e);
    }
    

    Note if you are not using the default laravel db connection then you need to do the following:

    DB::connection('connection_name')->pdo->beginTransaction();
    DB::connection('connection_name')->pdo->commit();
    DB::connection('connection_name')->pdo->rollBack();
    

提交回复
热议问题