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

标签 php laravel transactions closures

我正在使用 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)

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

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

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

关于php - Laravel - 从数据库事务闭包中获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31059540/

相关文章:

php - 错误: unknown key name 'CONCAT_WS' in sphinx query

php - 使用 PHP 的下拉菜单

PHP 在 json 数组中搜索

java - WebSphereExtendedJTATransactionLookup 和 WebSphereTransactionManagerLookup 之间的区别?

第 5 行的 php 语法错误

php - Laravel Eloquent 另一个表中列的总和

laravel - Vagrant Puppet 配置 - Pear 包

php - 验证多个复选框 laravel 5.2

c# - TransactionScope 包装 ORM 调用,第二次调用时出现 TransactionStateAborted.CreateAbortingClone 异常

javascript - CSS 过渡和 JS 同时切换