你好,我的数据库里有两个表:
当我添加新用户时,数据也会保存到user_profile表中。我正在考虑的情况是,由于某种原因,数据能够保存到用户表中,而不能保存到user_profile表中。
我希望删除user表中的数据,以避免记录中断,因为我的用户和user_profile表相互依赖。
实现这一目标的最佳途径是什么?
发布于 2015-09-14 09:45:09
您可以使用数据库事务。使用它们的最简单方法是
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();
}https://stackoverflow.com/questions/32561310
复制相似问题