【问题标题】:laravel excel with upserts not updating datalaravel excel 不更新数据
【发布时间】:2021-06-02 01:55:11
【问题描述】:

我有一个 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 文件导入到我的数据库中,我希望它得到更新。如果我的数据库中的任何记录具有相同的颜色、味道、气味和名称数据,则相同。

我的桌子:

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

有什么想法吗?

【问题讨论】:

    标签: php laravel laravel-excel


    【解决方案1】:

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

    除 SQL Server 之外的所有数据库都要求 uniqueBy 列具有“主”或“唯一”索引。

    要以自定义方式导入电子表格数据,您始终可以使用 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],
                        ...
                    ]
                );
            }
        }
    }
    

    【讨论】:

    • 不完全是我想要的,但真的很有帮助。谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-08-29
    • 2021-09-23
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多