1

用于将MaatwebsiteExcel 文件上传到数据库。

每行都有一个属性类型,例如“阁楼”或“别墅”。

我想收集每一行的每种属性类型。

使用以下功能将不起作用:

Excel::filter('chunk')->load($csv->getRealPath())->chunk(250, function ($results) {
    DB::table('prices')->truncate();

    foreach ($results as $row) {
        /**
         * @var CellCollection $row
         */

        array_push($this->property_types, $row->property_type);

        $price = Price::create($row->all());
    }
});

$this->property_types在函数中定义__construct如下:

public function __construct()
{
    $this->middleware('auth');

    $this->property_types = [];
}

这将导致一个空数组。

如此处所述,定义数组和using& 符号可能会解决问题,尽管这将返回相同的结果,即一个空数组。

$data = [];

Excel::filter('chunk')->load($csv->getRealPath())->chunk(250, function ($results) use (&$data) {
    DB::table('prices')->truncate();


    foreach ($results as $row) {
        /**
         * @var CellCollection $row
         */

        array_push($data, $row->property_type);

        $price = Price::create($row->all());
    }
});

我必须做什么才能在匿名函数内定义数据,并在函数外检索数据?

4

1 回答 1

1

问题是,默认情况下,该chunk()方法将在队列内异步处理您的匿名函数。由于该函数由队列内的工作人员运行,因此您将无法同步访问它在调用该chunk()方法的代码中处理的任何数据。

您可以通过false作为第三个参数传入该chunk()方法来阻止使用队列。

Excel::filter('chunk')
    ->load($csv->getRealPath())
    ->chunk(250, function ($results) {
        /* your code */
    }, false);

作为附加说明,您在truncate()回调中调用。我不知道这是否是故意的,但这会在每个处理的块上截断你的表。

于 2016-05-18T15:52:06.670 回答