簡體   English   中英

Laravel - 從DB Transaction Closure獲取變量

[英]Laravel - Get variable from a DB Transaction Closure

我正在使用Laravel 5 LAMP堆棧,我正在嘗試使用數據庫事務處理CSV導入。 代碼如下所示:

// Should contain any messages to pass back to the user
$results = [];

// Contains the total records inserted
$total = 0;

DB::transaction(function() use($csv_file, $results, $total) {

    // Some Code ...

    $total++;
    $results[] = 'Row 10 has some weird data...';
});

return view('plan.import')
    ->with('results', $results)
    ->with('total', $total);

最后,我的記錄被導入,但我的$ total和$ results仍然是空的,因為它們超出了閉包的范圍。 我知道他們在功能中被改變了,因為我已經介入它,看到它們發生了變化。 我無法想象如何讓他們退出該交易並將其返回給用戶。 任何人都可以幫忙嗎?

您可以替換以下行:

DB::transaction(function() use($csv_file, $results, $total)

有了這個:

DB::transaction(function() use($csv_file, &$results, &$total)

因此,函數內部所做的更改將反映在變量中,因為&創建變量的引用(傳遞變量引用)而不是按值傳遞它們。 檢查通過參考手冊。

或者,您可以從閉包內部返回變量,如:

$array = DB::transaction(function() use($csv_file, $results, $total) {

    // Some Code ...

    $total++;
    $results[] = 'Row 10 has some weird data...';
    return compact('total', 'results');
});

然后使用它像:

return view('plan.import')
->with('results', $array['results'])
->with('total', $array['total']);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM