Laravel - 从数据库事务关闭中获取变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31059540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Get variable from a DB Transaction Closure
提问by Captain Hypertext
I am working with a Laravel 5 LAMP stack, and I am trying to process a CSV import with a database transaction. Code looks like this:
我正在使用 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);
At the end of that, my records are imported, but my $total and $results are still empty, since they are outside the scope of the closure. I know they are being altered inside the function, because I've stepped through it, and seen them change. I just can't figure how to get them out of that transaction and return them to the user. Can anyone please help with this?
最后,我的记录被导入,但我的 $total 和 $results 仍然是空的,因为它们超出了闭包的范围。我知道它们在函数内部被改变,因为我已经通过它,看到它们发生了变化。我只是不知道如何让他们退出交易并将它们返回给用户。任何人都可以帮忙吗?
回答by The Alpha
You may replace the following line:
您可以替换以下行:
DB::transaction(function() use($csv_file, $results, $total)
with this:
有了这个:
DB::transaction(function() use($csv_file, &$results, &$total)
So the changes made inside the function will reflect in the variables because &
creates a reference of the variable (Passes the variable reference) instead of passing them by value. Check Passing by ReferenceManual.
因此,函数内部所做的更改将反映在变量中,因为&
创建了变量的引用(传递变量引用)而不是按值传递它们。检查通过参考手册。
Alternatively, you can return the variables from inside the closure like:
或者,您可以从闭包内部返回变量,例如:
$array = DB::transaction(function() use($csv_file, $results, $total) {
// Some Code ...
$total++;
$results[] = 'Row 10 has some weird data...';
return compact('total', 'results');
});
Then use it like:
然后像这样使用它:
return view('plan.import')
->with('results', $array['results'])
->with('total', $array['total']);