Issue
I've facing problem insert value using Excel Import.
And there is my App\Imports
<?php
namespace App\Imports;
use App\Models\Pelanggan;
use Maatwebsite\Excel\Concerns\ToModel;
class PelangganImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Pelanggan([
'id_pelanggan' => $row[0],
'nama_pelanggan' => $row[1],
'alamat1_pelanggan' => $row[2],
'alamat2_pelanggan' => $row[3],
'id_kategori_pelanggan' => $row[4],
'id_channel' => $row[5],
'id_outlet' => $row[6],
]);
if ($row [7]){
$dataArray['id_subdist'] = $row[7];
}
}
}
On Migrate table I was set default to "DUMMY"
$table->string('id_subdist',30)->default('DUMMY')->comment('id_subdist/dso');
I'm using laravel 8.6 and My database is MySql
Solution
If you have set the database table column default value then it will enter the default value if you are specifying any value at the time when you are entering a new row to the table.
When importing you can have a check and if id_subdist
is available then add to the database, if not let database handle it and add the default value automatically.
$dataArray = [
'id_pelanggan' => $row[0],
'nama_pelanggan' => $row[1],
'alamat1_pelanggan' => $row[2],
'alamat2_pelanggan' => $row[3],
'id_kategori_pelanggan' => $row[4],
'id_channel' => $row[5],
'id_outlet' => $row[6]
];
if ($row[7]){
$dataArray['id_subdist'] = $row[7];
}
return new Pelanggan($dataArray);
Database will automatically will enter the default value to id_subdist
if it is not available.
Answered By - Dula
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.