首页 > 解决方案 > 在导入时拆分分组数据

问题描述

我有一个如下的excel电子表格: 1

这将产生九个具有该属性的模型:

我试图使用 Laravel Excel 找到解决方案,但我被卡住了。问题是一行变成了三行,我不知道如何实现,因为我无法覆盖这些行。

<?php

namespace App\Imports;

use App\Models\MyModel;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Row;

//use Maatwebsite\Excel\Concerns\WithMapping;

class ForecastImport implements ToModel, OnEachRow
{
    function headingRow(): int { return 2; }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        dd($row);
        return new MyModel([
            'group' => $row[0],
            'column' => $row[1],
            'value' => $row[2]
        ]);
    }

    public function onRow(Row $row)
    {
        $entries = array_map(function($entry) {
            return [
                'group' => $entry[0],
                'column' => $entry[1],
                'value' => $rowentry2]
            ];
        }, array_chunk($row->toArray(), 3));
        /*foreach($entries as $entry) {
            $this->model($entry);
        }*/
        // One row became three
        return $entries;
    }
}

标签: phplaravellaravel-8laravel-excel

解决方案


看来您走在正确的轨道上。正如相关文档中所提到的,这个OnEachRow关注点可以让您更好地控制在非标准情况下发生的事情,其中​​整行不一定是直接的模型表示(与ToModel关注点相反)。该文档甚至建议不要将两者混合使用。

就您而言,是什么阻止您按照自己的方式填充模型?虽然我不太了解您模型的三场结构,但我建议您简单地像这样:

<?php

namespace App\Imports;

use App\Models\MyModel;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Row;

class ForecastImport implements OnEachRow
{
    function headingRow(): int { return 2; }

    public function onRow(Row $row)
    {
        //splitting the 9-column array into chunks of 3
        $entries = array_map(function($entry) {
            return [
                'group' => $entry[0],
                'column' => $entry[1],
                'value' => $entry[2]
            ];
        }, array_chunk($row->toArray(), 3));

        //populate a model with each chunk
        foreach($entries as $entry) {
            MyModel::create($entry);
        }
    }
}

但同样,我看不到与您正在解析的列和组的相关性,因为您只会分配值。无论如何,您可以自己修改它 - 重点是使用OnEachRow,您可以更自由地自己管理模型创建。在这种情况下,我们每行创建 3 个模型记录,所以我想这应该足够了。如果我误解了什么,请纠正我。快乐编码!


推荐阅读