如何在 Laravel 7 中导入 Excel 与 Table 关系?

How to Import Excel with Table Relation in Laravel 7?

我想问一下

我想使用 laravel-excel 包制作 excel 导入功能。其中,我导入的数据对另一个有关系值table.

所以,当我导入 excel 时,它会在 table 秒内保存数据。

第一个table,存储名称和文件路径等数据。而第二个 table,保存导入的 excel 文件的详细信息,并将关系添加到第一个 table.

下面是我拥有的两个 table

booked_vouchers:

booked_voucher_details:

以下是我在控制器中制作的代码,查看和导入文件。

形式

<form action="{{ route('booked.import')}}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group">
        <label for="name">Name</label>
        <input name="name" type="text" class="form-control" required>
    </div>
    <div class="form-group">
        <label for="file">File</label>
        <input name="file" type="file" class="form-control" required>
    </div>
    <button type="submit" class="btn btn-primary">Import</button>
</form>

控制器

    public function import(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|mimes:csv,xlx,xls,xlsx'
        ]);

        if ($validator->fails()) {
            return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
        }

        $data = new BookedVoucher();

        $data->name = $request->name;
        $fileName = time().'_'.$request->file->getClientOriginalName();
        $filePath = $request->file('file')->storeAs('reports', $fileName, 'public');

        $data->file = $filePath;
        $data->created_by = \Auth::user()->id;

        if ($data->save()) {
            Excel::import(new BookedVoucherDetailImport, $request->file('file'));
        }

        return redirect()->back()->with('success','Data have been imported');
    }

BookedVoucherDetailImport.php

<?php

namespace App\Imports;

use App\Model\BookedVoucher;
use App\Model\BookedVoucherDetail;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class BookedVoucherDetailImport implements ToModel, WithStartRow
{
    /**
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $data = BookedVoucher::first();
        return new BookedVoucherDetail([
            'booked_voucher_id'     => $data->id,
            'course_code'           => $row[0], 
            'voucher_code'          => $row[1],
            'user_name'         => $row[2],
            'status'                => 'OK'
        ]);
    }
}

如何将 booked_voucher_id 值设置为与在 excel 导入过程之前保存的 booked_voucher table 中的 id 值相同?

*目前,如果我使用 BookedVoucherDetailImport.php 文件中的代码,booked_voucher_details table 中的 booked_voucher_id 值的结果总是不正确的。

您可以将 BookedVoucher 传递给导入 class:

Excel::import(new BookedVoucherDetailImport($data), $request->file('file'));

然后将您的 BookedVoucherDetailImport 更新为:

<?php

namespace App\Imports;

use App\Model\BookedVoucher;
use App\Model\BookedVoucherDetail;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class BookedVoucherDetailImport implements ToModel, WithStartRow
{
    /**
     * @var BookedVoucher 
     */
    protected $bookedVoucher;

    /**
     * @param BookedVoucher $bookedVoucher
     */
    public function __construct(BookedVoucher $bookedVoucher)
    {
        $this->bookedVoucher = $bookedVoucher;
    }
    
    /**
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }

    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        return new BookedVoucherDetail([
            'booked_voucher_id' => $this->bookedVoucher->id,
            'course_code'       => $row[0],
            'voucher_code'      => $row[1],
            'user_name'         => $row[2],
            'status'            => 'OK',
        ]);
    }
}