Laravel导入CSV(如果存在)显示消息对话框

问题描述 投票:0回答:1

如何在数据库导入之前检查CSV文件是否已存在,如果是,则显示将更新现有记录的消息。因此,如果用户单击是,则导入方法将起作用并添加不重复的记录,如果存在重复记录,则将更新现有记录。

希望很清楚,无论如何都要做到这一点请澄清。

控制器:

public function store(Request $request)
{
    $upload=$request->file('upload-file');
    $filePath=$upload->getRealPath();
    $file=fopen($filePath,'r');
    $header=fgetcsv($file);
    $escapedHeader=[];
    foreach ($header as $key => $value) {
        $header=strtolower($value);

        $escapedItem=preg_replace('/[^a-z]/','', $header);
        array_push($escapedHeader, $escapedItem);

    }
    while($columns=fgetcsv($file))
    {
        if($columns[0]=="")
        {
            continue;
        }
        foreach ($columns as $key => $value) {
            $value=preg_replace('/\D/','', $value);
        }
        $data=array_combine($escapedHeader, $columns);
        $details=$data['details'];
        $postingdate=$data['postingdate'];
        $description=$data['description'];
        $amount=$data['amount'];
        $type=$data['type'];
        $slip=$data['checkorslip'];
        $addchecks=Checks::firstOrNew(['details'=>$details, 
            'postingdate'=>$postingdate,'description'=>$description,
            'amount'=>$amount,'type'=>$type]);

        $addchecks->postingdate=$postingdate;
        $addchecks->description=$description;
        $addchecks->amount=$amount;
        $addchecks->type=$type;
        $addchecks->slip=$slip;

        $addchecks->save();
    }
}
php laravel
1个回答
0
投票

首先,您可以在表中记录导入。像文件名,导入日期,任何错误,......

要查看文件是否已导入,请创建其内容的哈希并将其存储到所述日志记录表中。上传新文件时,创建内容的哈希值,将其与日志记录表中的哈希值进行比较...如果已经存在,则抛出错误,如果不导入它。

© www.soinside.com 2019 - 2024. All rights reserved.