簡體   English   中英

laravel excel 不更新數據

[英]laravel excel with upserts not updating data

我有一個 csv 文件,里面有數據。 我想將它導入我的數據庫。 如果 csv 文件中有重復數據,我不希望它創建新的重復記錄,我想要更新它。

但問題是,它正在創造新的重復記錄。

Controller(簡稱):

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)    |      |
...

I'm using Laravel 8, Php 8.0.2 and Mysql 8. Laravel excel is version 3.1

我的參考資料:

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

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

有任何想法嗎?

我不確定Laravel Excel 中的 Upserts是你想要的。 具體來說,文檔中列出的條件(在我看來)過於嚴格。

除了 SQL 服務器之外的所有數據庫都要求 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],
                    ...
                ]
            );
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM