DB::transaction(function () use ($uid, $roleId) {
RoomUserRole::insert([
'uid' => $uid,
'role_id' => $roleId,
'created_at' => LARAVEL_START,
'updated_at' => LARAVEL_START
]);
RoomUserRoleLog::insert([
'uid' => $uid,
'handle_type' => 1,
'admin_uid' => Auth::user()->id,
'created_at' => LARAVEL_START,
'updated_at' => LARAVEL_START
]);
});
以上mysql 第二句会报错抛出一个异常, 查看数据库时第一句依然出入成功。查看laravel的DB::transaction()的使用
原因以及解决方法:
项目使用多个数据库配置,DB::transaction()使用的是默认库的事务操作。所以要指定哪个数据库的事务,以上代码调整:
DB::connection('mysql2')->transaction(function () use ($uid, $roleId) {
RoomUserRole::insert([
'uid' => $uid,
'role_id' => $roleId,
'created_at' => LARAVEL_START,
'updated_at' => LARAVEL_START
]);
RoomUserRoleLog::insert([
'uid' => $uid,
'handle_type' => 1,
'admin_uid' => Auth::user()->id,
'created_at' => LARAVEL_START,
'updated_at' => LARAVEL_START
]);
}); // 这样你会发现事务才正常回滚
同样
DB::connection('mysql_chat_room')->beginTransaction();
DB::connection('mysql_chat_room')->commit();
DB::connection('mysql_chat_room')->rollBack(); // 指定库,不然都会跑默认配置库的事务
有话要说