猿问

为什么我使用laravel框架的事务 返回数据到客户端 客户端接收不到这个值??

public function create_order()
{

DB::transaction(function () {
    $request = request();
    $check_report = new checkreportEcgsModel();
    $check_report_data = $check_report->add_check_report(request()->all());
    if (!empty($check_report_data)) {
        $order = new OrderModel();
        $order_data = $order->add_order($check_report_data);
        if (!empty($order_data)) {
            $payment = new PaymentModel();
            $payment_data = $payment->add_payment($order_data);
            if (empty($payment_data)) {
                return ['status' => 0, 'msg' => '支付记录生成失败'];
            }
        } else {
            return ['status' => 0, 'msg' => '订单记录生成失败'];
        }
        //为什么客户端接收不到这个值??
        return ['status' => 1, 'msg' => '订单创建成功', 'oid' =>$order_data->orderid];
    } else {
        return ['status' => 0, 'msg' => '订单创建失败,请重新创建!'];
    }
});

}
这是响应的信息 是空的 我服务器 数据是绝对处理完了 我知道是因为事务的原因 但是 我该怎么合理的处理这个事务

白衣染霜花
浏览 430回答 2
2回答

慕后森

因为你在闭包函数里面return的话实际上是把结果返回到transaction这个function里面去了,所以你需要再return一次把代码改成 public function create_order() { return DB::transaction(function () { $request = request(); $check_report = new checkreportEcgsModel(); $check_report_data = $check_report->add_check_report(request()->all()); if (!empty($check_report_data)) { $order = new OrderModel(); $order_data = $order->add_order($check_report_data); if (!empty($order_data)) { $payment = new PaymentModel(); $payment_data = $payment->add_payment($order_data); if (empty($payment_data)) { return ['status' => 0, 'msg' => '支付记录生成失败']; } } else { return ['status' => 0, 'msg' => '订单记录生成失败']; } //为什么客户端接收不到这个值?? return ['status' => 1, 'msg' => '订单创建成功', 'oid' =>$order_data->orderid]; } else { return ['status' => 0, 'msg' => '订单创建失败,请重新创建!']; } }); } 你可以看一下transaction的源码 public function transaction(Closure $callback, $attempts = 1) { for ($a = 1; $a <= $attempts; $a++) { $this->beginTransaction(); // We'll simply execute the given callback within a try / catch block // and if we catch any exception we can rollback the transaction // so that none of the changes are persisted to the database. try { $result = $callback($this); $this->commit(); } // If we catch an exception, we will roll back so nothing gets messed // up in the database. Then we'll re-throw the exception so it can // be handled how the developer sees fit for their applications. catch (Exception $e) { if ($this->causedByDeadlock($e) && $this->transactions > 1) { --$this->transactions; throw $e; } $this->rollBack(); if ($this->causedByDeadlock($e) && $a < $attempts) { continue; } throw $e; } catch (Throwable $e) { $this->rollBack(); throw $e; } return $result; } }

慕的地8271018

你这代码好奇怪啊. try { DB::translation(function () { /** TODO */ }); return ['返回成功']; } catch (Exception $e) { return ['返回失败']; } 感觉你就是瞎写. 都不知道DB::translation() 这函数咋用. DB::translation()里面写操作数据库的代码就好了, 你把那把取数据, 判断操作都放进去是要搞啥?
随时随地看视频慕课网APP
我要回答