gpt4 book ai didi

excel - 导入excel时跳过重复行

转载 作者:行者123 更新时间:2023-12-04 20:04:10 28 4
gpt4 key购买 nike

我想将一些excel数据导入laravel数据库。我已成功完成此操作,但我第二次尝试仅导入 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],
]);
}
}
这是我的 Controller
<?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>
请告诉我如何解决它或给我任何建议。

最佳答案

您可以使用 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],
]);
}
}
}

关于excel - 导入excel时跳过重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57940973/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com