【发布时间】:2019-07-11 08:56:27
【问题描述】:
我在 Laravel Maatwebsite Excel 3.1 上使用 Excel 导入数据。但是当数据库中有相同的数据(主键)时,就会出现错误消息
完整性约束违规:1062 键的重复条目“188281” '初级'
我尝试了解 Maat 网站的文档,但仍然失败
public function storeData(Request $request)
{
//VALIDASI
$this->validate($request, [
'file' => 'required|mimes:xls,xlsx'
]);
if ($request->hasFile('file')) {
$file = $request->file('file');
// dd($file); //GET FILE;
Excel::import(new MahasiswaImport, $file); //IMPORT FILE
return redirect('/mahasiswa')->with(['status' => 'Upload success']);
}
return redirect('/mahasiswa')->with(['error' => 'Please choose file before']);
}
<?php
namespace App\Imports;
use App\Mahasiswa;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\Importable;
class MahasiswaImport implements ToModel, WithHeadingRow, WithChunkReading, ShouldQueue
{
use Importable;
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Mahasiswa([
'nim' => $row['nim'],
'slug' => str_slug($row['nim']),
'nama_mahasiswa' => $row['nama_mahasiswa'],
'email' => $row['email'],
'kode_kelas' => $row['kode_kelas'],
'alamat' => $row['alamat'],
'kode_jurusan' => $row['kode_jurusan'],
'kode_tahun_akademik' => $row['kode_tahun_akademik'],
'no_hp' => $row['no_hp'],
'tempat_lahir' => $row['tempat_lahir'],
// 'tanggal_lahir' => $row['tanggal_lahir'],
'password' => $row['password']
]);
}
public function chunkSize(): int
{
return 1000;
}
}
【问题讨论】:
-
你能在你的模型函数中
dd($row)并提供它吗? -
好的。我已经进入帖子了
-
你有没有尝试过这样的事情:
$data = Mahasiswa::create([ 'nim' => $row['nim'], 'slug' => str_slug($row['nim']), 'nama_mahasiswa' => $row['nama_mahasiswa'], 'email' => $row['email'], 'kode_kelas' => $row['kode_kelas'], 'alamat' => $row['alamat'], 'kode_jurusan' => $row['kode_jurusan'], 'kode_tahun_akademik' => $row['kode_tahun_akademik'], 'no_hp' => $row['no_hp'], 'tempat_lahir' => $row['tempat_lahir'], 'password' => $row['password'] ]); return $data; -
您的错误来自 sql,因为您的主键有重复键。来自
$row的一些数据是您的主键吗? -
是的。 NIM 是主键,。因此,如果数据已经在数据库中,则跳过该数据
标签: php laravel laravel-5 maatwebsite-excel laravel-excel