Laravel 导入:如何用 id 替换导入的行值?

Laravel Imports: How to replace imported row value by id?

所以我有这个代码:

PengajuanDetailController.php

public function import(Request $request){
    $file = $request->file('file');
    $namaFile = $file->getClientOriginalName();
    $file->move('DataDetailPengajuan', $namaFile);

    Excel::import(new SubmissionDetailImport, public_path('/DataDetailPengajuan/'.$namaFile));
    return redirect()->back()->with("status", ["status" => true, "message" => "Success importing detail"]);
}

SubmissionDetailImport.php

<?php

namespace App\Imports;

use App\SubmissionDetail;
use Maatwebsite\Excel\Concerns\ToModel;

class SubmissionDetailImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new SubmissionDetail([
            'submission_id' => $row[1],
            'nama_barang' => $row[2],
            'image_path' => $row[3],
            'jumlah' => $row[4],
            'harga_satuan' => $row[5],
            'harga_total' => $row[6],
            'keterangan' => $row[7],
        ]);
    }
}

我想让 'submission_id' 的导入行值等于一个 id,

例如:http://127.0.0.1:8000/pengajuan/4/

'submission_id'的行值变成了“/4/”的4而不是原来导入的值,怎么办?

您只需将 Url 参数传递给进口商即可。

public function import(Request $request, $submissionId) {
    ...

     Excel::import((new SubmissionDetailImport)->setSubmissionId(submissionId), public_path('/DataDetailPengajuan/'.$namaFile));

现在我们需要 Excel 导入器 class 上的逻辑。将其添加为 属性 并为其定义 setter。

class SubmissionDetailImport implements ToModel
{
    private $submissionId;

    public function setSubmissionId($submissionId) {
        $this->submissionId = $submissionId;
    }

    public function model(array $row)
    {
        return new SubmissionDetail([
            'submission_id' => $this->submissionId,
            'nama_barang' => $row[2],
            'image_path' => $row[3],
            'jumlah' => $row[4],
            'harga_satuan' => $row[5],
            'harga_total' => $row[6],
            'keterangan' => $row[7],
        ]);
    }
}