首页 > 解决方案 > 跳过不在 Laravel 关系表中的行

问题描述

我在跳过行导入 excel / csv Laravel 到 sql 数据库时遇到问题。有两个关系表,分别是品牌表和项目表。我使用 maatwebsite-excel。

Brand Table:
id  brand       desc
1   AA      details AA
2   AB      details AB
3   AC      details AC

Item Table
id  date        brand_id        buyer
1   09-02-21        3       Andy
2   09-02-21        1       Jhon
3   09-02-21        2       Daniel

这是一个包含标题的导入文件 excel / csv:

(date)  (brand) (buyer)
10-02-21    AC  Reimon
10-02-21    AC  David
10-02-21    AB  Michel
10-02-21    ZA  Susy
10-02-21    AA  Edgar
10-02-21    NK  Rhein

只有 Brands Table 中的品牌会保存到数据库中。不存在的品牌将被跳过。我们想要的是这种类型的数据:

(date)  (brand) (buyer)
10-02-21    AC  Reimon
10-02-21    AC  David
10-02-21    AB  Michel
10-02-21    AA  Edgar

这是我的 ItemImport.php

class ItemImport implements ToCollection, WithCalculatedFormulas, WithChunkReading, ShouldQueue, WithCustomCsvSettings
{
    public function collection(Collection $collection)
    {

    $collection = $collection->toArray();
    //dd($collection);

        foreach ($collection as $key => $row){
            if($key >= 0){

                $brand= Brand::where("brand","like","%".$row['1']."%")->first();
                $row['1'] = $brand->id;
                 
                Item::create([
                    'date' => $row['0'],
                    'brand_id' => $row['1'], 
                    'buyer' => $row['3']
                ]);
                           
            }
        }
    }
}

在代码中,原来没有跳行功能,所以所有的行都输入到数据库中。即使我想摆脱以下数据:

(date)  (brand) (buyer)
10-02-21    ZA  Susy
10-02-21    NK  Rhein

非常感谢愿意解答我困难的各位。:)

标签: laravelimportphpexcelmaatwebsite-excel

解决方案


希望这对你有用,试试吧。

class ItemImport implements ToCollection, WithCalculatedFormulas, WithChunkReading, 
ShouldQueue, WithCustomCsvSettings
{
    public function collection(Collection $collection)
    {

    $collection = $collection->toArray();
    //dd($collection);
    $array_of_names_excluded=['ZA', 'NK'];

        foreach ($collection as $key => $row){
            if($key >= 0){

                $brand= Brand::whereNotIn("brand", $array_of_names_excluded)
                        ->where("brand","like","%".$row['1']."%")->first();

                if($brand){
                    $row['1'] = $brand->id;
                 
                    Item::create([
                        'date' => $row['0'],
                        'brand_id' => $row['1'], 
                        'buyer' => $row['3']
                    ]);
                }           
            }
        }
    }
}

推荐阅读