Laravel-从数据库事务闭包中获取变量


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']);