Laravel - 从DB Transaction Closure获取变量

Cap*_*ext 8 php closures transactions laravel

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

最后,我的记录被导入,但我的$ total和$ results仍然是空的,因为它们超出了闭包的范围.我知道他们在功能中被改变了,因为我已经介入它,看到它们发生了变化.我无法想象如何让他们退出该交易并将其返回给用户.任何人都可以帮忙吗?

The*_*pha 34

您可以替换以下行:

DB::transaction(function() use($csv_file, $results, $total)
Run Code Online (Sandbox Code Playgroud)

有了这个:

DB::transaction(function() use($csv_file, &$results, &$total)
Run Code Online (Sandbox Code Playgroud)

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

或者,您可以从闭包内部返回变量,如:

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

    // Some Code ...

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

然后使用它像:

return view('plan.import')
->with('results', $array['results'])
->with('total', $array['total']);
Run Code Online (Sandbox Code Playgroud)