跳过不在 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

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

(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

非常感谢愿意为我解答疑难的你们。 :)

解决方法

您可以简单地检查要排除插入数据库的项目。

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 && $row['1']!='ZA' && $row['1']!='NK'){

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

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

class ItemImport implements ToCollection,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","%".$row['1']."%")->first();

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