我想在laravel数据库中导入一些Excel数据。我已成功完成此操作,但我第二次尝试仅导入excel更新数据并跳过重复的行。我正在使用laravel 6和mattwebsite 3.1
这是我的导入课程
<?php
namespace App\Imports;
use App\Contact;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
class ContactsImport implements ToModel, WithStartRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function startRow(): int
{
return 2;
}
public function model(array $row)
{
return new Contact([
'name' => $row[0],
'designation' => $row[1],
'email' => $row[2],
'phone' => $row[3],
]);
}
}
这是我的控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Arr;
use App\Imports\ContactsImport;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
class ExcelController extends Controller
{
public function importContact()
{
Excel::import(new ContactsImport, request()->file('file'));
return back();
}
}
HTML表单
<form action="{{ route('contact.import')}}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" class="mb-3">
<br>
<button class="btn btn-success">Import User Data</button>
</form>
请告诉我如何解决或给我任何建议。
答案 0 :(得分:0)
您可以使用OnEachRow concern:
namespace App\Imports;
use App\Contact;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
class UsersImport implements OnEachRow
{
public function onRow(Row $row)
{
$row = $row->toArray();
$contact = Contact::firstOrCreate(
['email' => $row[2]],
[
'name' => $row[0],
'designation' => $row[1],
'email' => $row[2],
'phone' => $row[3],
]
);
if (! $contact->wasRecentlyCreated) {
$contact->update([
'name' => $row[0],
'designation' => $row[1],
'phone' => $row[3],
]);
}
}
}