laravel excel 更新插入不更新数据

laravel excel with upserts not updating data

我有一个包含数据的 csv 文件。我想将它导入我的数据库。如果csv文件中有重复的数据,我不希望它创建新的重复记录,我想要的是更新它。

但问题是,它正在创建新的重复记录。

控制器(缩写):

Excel::import(new FruitImport, $request->file('fruits_file'), \Maatwebsite\Excel\Excel::XLSX);

导入文件(缩写):

class FruitImport implements ToModel, WithUpserts, ... {
    public function model(array $row) {
        return new Fruit([
            'color' => $row[0],
            'taste' => $row[1],
            'smell' => $row[2],
            'name' => $row[3],
            'price' => $row[4],
            'supplier_id' => $row[5],
            ...
         ]);
    }

    public function uniqueBy() {
        return ['color', 'taste', 'smell', 'name'];
    }

    ...
}

所以基本上,如果我将包含具有相同颜色、味道、气味、名称的行的 csv 文件导入到我的数据库中,我希望它得到更新。如果我的数据库中的任何记录具有相同的颜色、味道、气味和名称数据,情况相同。

我的table:

Field    | Type        | Key  | ...
id       | big int un..| Pri  |
color    | varchar(12) |      |
taste    | varchar(12) |      |
smell    | varchar(12) |      |
name     | char(20)    |      |
...

我正在使用 Laravel 8、Php 8.0.2 和 Mysql 8。 Laravel excel 是版本 3.1

我的参考资料:

https://laravel.com/docs/8.x/eloquent#upserts

https://docs.laravel-excel.com/3.1/imports/model.html#upserting-models

有什么想法吗?

我不确定 Upserts in Laravel Excel 是否是您想要的。具体来说,文档中列出的条件(在我看来)过于严格。

All databases except SQL Server require the uniqueBy columns to have a "primary" or "unique" index.

要以自定义方式导入电子表格数据,您始终可以使用 ToCollection 关注点。这将使您能够完全控制条目的保存方式。
https://docs.laravel-excel.com/3.1/imports/collection.html

使用 updateOrCreate() 方法查找具有您指定选项的现有条目,方法是将它们传递到第一个数组,其余数据传递到第二个数组。 https://laravel.com/docs/8.x/eloquent#upserts

class FruitImport implements ToCollection ... 
{    
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) 
        {
            Fruit::updateOrCreate(
                [
                    'color' => $row[0],
                    'taste' => $row[1],
                    'smell' => $row[2],
                    'name' => $row[3]
                ],
                [
                    'price' => $row[4],
                    'supplier_id' => $row[5],
                    ...
                ]
            );
        }
    }
}