我正在尝试使用WithValidation关注在导入数组上查找重复的行(稍后将使用SkipsOnError删除重复的行)。但是我的导入类中的验证集似乎找不到重复的行。 当我上传包含重复数据的excel文件(只是没有标题的列)时,没有错误返回并且所有行都导入到数据库中
<?php
namespace App\Imports;
use App\Contactlist;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;
class ContactsImport implements ToModel, WithValidation
{
use Importable;
private $data;
public function __construct(array $data = [])
{
$this->data = $data;
}
public function model(array $row)
{
if (!isset($row[0])) {
return null;
}
return new Contactlist(array_merge([
'nums' => $row[0],
], $this->data));
}
public function rules(): array
{
return [
//find duplicate records
'0.*' => 'distinct',
//'*.0' => 'distinct' Tried this also
];
}
}
我的控制器的代码段
$data = [
'contact_id' => $contact->id,
];
Excel::import(new ContactsImport($data), request()->file('contact_file'));
答案 0 :(得分:0)
将此工作导入收藏集
namespace App\Imports;
use App\Contactlist;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class ContactsImport implements ToCollection
{
private $data;
public function __construct(array $data = [])
{
$this->data = $data;
}
/**
* @param array $row
*/
public function collection(Collection $rows)
{
// Initialize number
$numbers = array();
foreach ($rows as $row) {
//Skip empty rows
if (!isset($row[0]))
continue;
//Skip number previously added using in_array
if (in_array($row[0], $numbers))
continue;
Contactlist::create(array_merge([
'nums' => $row[0],
], $this->data));
// Add new number to array
$numbers[] = $row[0];
}
}
}
答案 1 :(得分:0)
class ExempleImport implements ToCollection, WithHeadingRow
{
/** @var Collection */
public $collection;
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
$this->collection = $collection->transform(function ($row) {
$this->validationFields($row);
return [
'curso' => $row['curso'],
'marca' => $row['marca'],
'status' => $row['status_do_curso'],
'emissor' => $row['emissor_cliente'],
'nome_da_conta' => $row['nome_da_conta'],
];
});
}
public function validationFields( $row )
{
$customMessages = [
'required' => 'O campo :attribute deve estar preenchido'
];
Validator::make($row->toArray(), [
'curso' => 'required',
'marca' => 'required',
'status_do_curso' => 'required',
'emissor_cliente' => 'required',
'nome_da_conta' => 'required',
], $customMessages)->validate();
}
}
在您的控制器中
$exampleImport = new ExampleImport;
try{
Excel::import( $exampleImport, $updateFile);
}catch ( ValidationException $e ){
return response()->json(['success'=>'errorList','message'=> $e->errors()]);
}