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 仍然是空的,因为它们在闭包的范围之外。我知道它们在函数内部被改变,因为我已经逐步完成它,并且看到它们发生了变化。我只是不知道如何将它们从该交易中取出并 return 给用户。有人可以帮忙吗?

您可以替换以下行:

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

有了这个:

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

因此函数内部所做的更改将反映在变量中,因为 & 创建变量的引用(传递变量引用)而不是按值传递它们。检查 Passing by Reference 手册。

或者,您可以 return 闭包内部的变量,例如:

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