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' => '訂單記錄生成失敗'];
}
//為什么客戶端接收不到這個(gè)值??
return ['status' => 1, 'msg' => '訂單創(chuàng)建成功', 'oid' =>$order_data->orderid];
} else {
return ['status' => 0, 'msg' => '訂單創(chuàng)建失敗,請重新創(chuàng)建!'];
}
});
}這是響應(yīng)的信息 是空的 我服務(wù)器 數(shù)據(jù)是絕對處理完了 我知道是因?yàn)槭聞?wù)的原因 但是 我該怎么合理的處理這個(gè)事務(wù)
2 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
因?yàn)槟阍陂]包函數(shù)里面return的話實(shí)際上是把結(jié)果返回到transaction這個(gè)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' => '訂單記錄生成失敗'];
}
//為什么客戶端接收不到這個(gè)值??
return ['status' => 1, 'msg' => '訂單創(chuàng)建成功', 'oid' =>$order_data->orderid];
} else {
return ['status' => 0, 'msg' => '訂單創(chuàng)建失敗,請重新創(chuàng)建!'];
}
});
}
你可以看一下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
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
你這代碼好奇怪啊.
try {
DB::translation(function () { /** TODO */ });
return ['返回成功'];
} catch (Exception $e)
{
return ['返回失敗'];
}
感覺你就是瞎寫. 都不知道DB::translation() 這函數(shù)咋用.
DB::translation()里面寫操作數(shù)據(jù)庫的代碼就好了, 你把那把取數(shù)據(jù), 判斷操作都放進(jìn)去是要搞啥?
- 2 回答
- 0 關(guān)注
- 452 瀏覽
添加回答
舉報(bào)
0/150
提交
取消