Laravel excel 验证两列的组合不重复

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

我有一个要求,其中我需要确保用户上传的 Excel 文件没有重复的行。 2 个特定的列。

示例:

在下面的代码片段中,我想标记出第 1 行和第 2 行包含

COMPANY_CODE
CLERK_CODE
的重复组合:

如果发现这样的重复组合,我想拒绝导入整个文件并让用户知道问题出在哪里。

有什么线索吗?

php laravel laravel-5.8 maatwebsite-excel laravel-excel
2个回答
1
投票

不确定 Maat/Laravel Excel 是否可以轻松解决这个问题。因此,我继续创建关联数组,其中键作为两列的串联,我不想在 Excel 中重复。

然后我使用 foreach 循环手动检查,如果关联数组中存在键,则意味着 Excel 中存在重复条目。

下面是一些示例代码供参考:

        $array = Excel::toArray(new MyExcelImport(), request()->file);

        $assoc_array = array();
        foreach ($array[0] as $key => $value) {
            $new_key = $value['company_code'] . $value['clerk_code'];

            // Presence of combination of company_code and clerk_code in the assoc_array indicates that
            // there is duplicate entry in the Excel being imported. So, abort the process and report this to user.
            if (array_key_exists($new_key, $assoc_array)) {
                return response()->json("Combination of company_code: " .
                    $value['company_code'] .
                    " and clerk_code: " .
                    $value['clerk_code'] .
                    " is duplicate in the file being imported. Please correct same and retry upload.", 422);
            }

            $assoc_array[$new_key] = $value;
        }

希望这可以帮助有类似需求的人!


0
投票

我使用 Laravel Excel 的内置函数prepareForValidation() 解决了这个问题。

在其中我创建了一个名为composite_column 的新列。

public function prepareForValidation($data, $index)
{
    $temp=[];
    foreach (['COMPANY_CODE', 'CLERK_CODE'] as $key => $value) {
        $temp[] = $data[$value];
    }
    $composite_column = implode('_', $temp);
    $data['composite_column']=$composite_column;

    return $data;
}

在构造部分中,我创建了一个包含复合键数据行的属性

public $exist_composite_column;

public function __construct()
{
    $this->exist_composite_column = YourModels::
        get()->map(function ($models) {
        return "{$models->COMPANY_CODE}_{$models->CLERK_CODE}";
    });
}

在验证部分我验证创建的列composite_column

public function rules(): array
{
    return [
        ...
        'composite_column' => [//variable
            'required',
            'strings',
            Rule::notIn($this->exist_composite_column),//variable
        ],
    ];
}
© www.soinside.com 2019 - 2024. All rights reserved.