Laravel excel,在数据库中保存后更新行

stszievb  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(158)

Laravel(9)和PHP(8.1)中的项目。
我想导入一个excel文件并使用maatwebsite/excel(3.1)包。
我可以导入一个文件,并将该文件保存到模型中,如下所示:
导入类:

class BankTransfersHistoryImport implements ToModel, WithHeadingRow, WithValidation, WithBatchInserts
{
    use Importable;

    private $rows;

    public function __construct()
    {
        $this->rows = collect();
    }

/**
 * @param array $row
 *
 * @return \Illuminate\Database\Eloquent\Model|null
 */
    public function model(array $row)
    {
        $bankTransferHistory = new BankTransfersHistory([    
            'loanId' => $row['loanId'],
            'actionDate' => transformDate($row['actionDate']),
            'worth' => $row['worth'],
            .
            .
        ]);

        $this->rows->push($bankTransferHistory);
        return $bankTransferHistory;
    }

    /**
     * Returns Imported Data
     *
     * @return \Illuminate\Support\Collection
     */
    public function getImportedData(): \Illuminate\Support\Collection
    {
        return $this->rows;
    }

    public function headingRow(): int
    {
        return 2;
    }

    public function rules(): array
    {
        return [ 
            '*.loanId' => ['required', 'numeric'],
            ... some roles ...
        ];
    }
}

控制器:

public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xls,xlsx',
        ]);

        $file = $request->file('file');

        $import = new BankTransfersHistoryImport;

        try {
            // date validation
            $collection = $import->toCollection($file);
            ... some validation about the date ...

            $import->import($file);
            $getImportedData = import->getImportedData();
            ... check and update rows ...

            return [
                "message" => some message,
                "data" => [
                    some data
                ],
            ];

        } catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
            $failures = $e->failures();

            foreach ($failures as $failure) {
                $failure->row(); // row that went wrong
                $failure->attribute(); // either heading key (if using heading row concern) or column index
                $failure->errors(); // Actual error messages from Laravel validator
                $failure->values(); // The values of the row that has failed.
            }
            return $failures;
      }

我的问题是:

如果我在保存数据后可以得到文件的响应,那么就会给予带有保存的行ID的数据。
在某些情况下,我将不得不更新行。这就是为什么我想获得ID。
现在,在检查和更新行部分,我按loanId + actionDate更新行。
就像这样:
代码:$getImportedData = import->getImportedData();
数据将类似于:

[
    {
        "id": 1,
        "loanId": 21001,
        "actionDate": "2020-01-02T00:00:00.000000Z",
        "worth": 2997.09,
        "offerId": 1,
    },
    {
        "id": 2,
        "loanId": 21002,
        "actionDate": "2020-01-02T00:00:00.000000Z",
        "worth": 3000,
        "offerId": 10,
    },
]
jdgnovmf

jdgnovmf1#

我的问题的解决方案。

为了保存信息并获取每个已保存行的ID,我做了几件事。

我更改了导入类。

  • 首先,我将create从ToModel更改为ToCollection
  • 我删除了WithBatchInserts,因为此方法不适用于ToCollection

接下来,我调用了getImportedData函数。

这就是我在DB中创建的所有行的ID。

这解决了我获取与每行ID一起保存的信息的问题,并在必要时执行验证+更新。

代码如下。
一张小纸条:

  • 我在'getImportedData'函数中将单词rows更改为data
  • 我把所有文件都保存在系统里。
导入类:
class BankTransfersHistoryImport implements ToCollection, WithHeadingRow, WithValidation
{
    use Importable;

    private $data;

    public function __construct()
    {
        $this->data = collect();
    }

/**
 * @param array $row
 *
 * @return \Illuminate\Database\Eloquent\Model|null
 */
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $bankTransferHistory = BankTransfersHistory::create([
                'loanId' => $row['loanId'],
                'actionDate' => transformDate($row['actionDate']),
                'worth' => $row['worth'],
                .
                .
            ]);

            $this->data->push($bankTransferHistory);
        }
    }

    /**
     * Returns Imported Data
     *
     * @return \Illuminate\Support\Collection
     */
    public function getImportedData(): \Illuminate\Support\Collection
    {
        return $this->data;
    }

    public function headingRow(): int
    {
        return 2;
    }

    public function rules(): array
    {
        return [ 
            '*.loanId' => ['required', 'numeric'],
            ... some roles ...
        ];
    }
}
存储控制器:
public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xls,xlsx',
        ]);

        $file = $request->file('file');

        $import = new BankTransfersHistoryImport;

        try {
            // date validation
            $collection = $import->toCollection($file);
            ... some validation about the date ...

            // save the file in the system
            $fileName = time() . '-' . $file->getClientOriginalName();
            $file->storeAs('import bank transfers history', $fileName);

            $import->import($file);
            $importedData = $import->getImportedData(); // data after save in DB
            ... check and update rows ...

            return [
                "message" => some message,
                "data" => [
                    some data
                ],
            ];

        } catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
            $failures = $e->failures();

            foreach ($failures as $failure) {
                $failure->row(); // row that went wrong
                $failure->attribute(); // either heading key (if using heading row concern) or column index
                $failure->errors(); // Actual error messages from Laravel validator
                $failure->values(); // The values of the row that has failed.
            }
            return $failures;
        }
    }

相关问题