版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
<?php
// 开启事务
DB::beginTransaction();
// 数据处理
try {
$user = new User;
$user->username = $username;
$user->nickname = '测试昵称';
$user->password = Hash::make($password);
$user->pic = 'xxoo.jpg';
$user->status = 1;
// 添加
if ( !$user->save() ) {
throw new \Exception("1");
}
$id = $user->id;
$user_detail = new UserDetail;
$user_detail->u_id = $id;
$user_detail->created_at = $time;
$user_detail->updated_at = $time;
$user_detail->phone = $phone;
$user_detail->email = $email;
// 添加
if ( !$user_detail->save() ) {
throw new \Exception("2");
}
DB::commit();
return response()->json(['code'=>2000, 'msg'=>'增加成功!']);
}
catch (\Exception $e) { // 捕获异常
DB::rollBack();
return response()->json(['code'=>2001, 'msg'=>'添加失败!']);
}