回滚数据库操作

时间:2015-09-14 09:24:51

标签: laravel eloquent

您好我的数据库中有两个表:

  1. 用户
  2. user_profiles
  3. 当我添加新用户时,数据也会保存到user_profile表中。我正在考虑一种情况,由于某种原因,数据能够保存到用户表而不是user_profile表。

    我希望删除users表中的数据以避免任何损坏的记录,因为我的user和user_profile表彼此依赖。

    实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用database transactions。最简单的使用方法是

DB::transaction(function()
{
    // Do something that alters 'users' table
    // Do something that alters 'user_profiles' table
});

如果上述任何操作失败(抛出异常),则所有操作都将被取消,您的数据库将不受影响。如果您需要对事务进行更多控制,可以执行此操作

try {
    DB::beginTransaction();

    // Do something that alters 'users' table
    // Do something that alters 'user_profiles' table

    if($somethingWentWrong)
        throw new Exception('something went wrong');

    // Everything OK
    DB::commit();

} catch (\PDOException $e) {

    // something went wrong with the database
    DB::rollBack();
} catch (\Exception $e) {

    // something went wrong
    DB::rollBack();
}
相关问题