【发布时间】:2020-10-26 07:38:26
【问题描述】:
我正在尝试将多行从 Excel 文件导入数据库。如果行数等于或大于 5,则记录成功添加到数据库中,但如果我尝试少于 5 条记录,则会出现 SQL 错误。
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'customer_name' cannot be null (SQL: insert into `shipments` (`user_id`, `customer_name`, `customer_address`, `customer_email`, `customer_phone`, `destination_country`, `destination_city`, `service_type`, `tb_date`, `tb_time`, `pickup_location`, `product_name`, `quantity`, `consignment_no`, `weights_id`, `product_value`, `product_reference`, `remarks`, `status`, `updated_at`, `created_at`) values (2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1220125, 1, ?, ?, ?, Booked, 2020-10-26 12:26:29, 2020-10-26 12:26:29))
这是我的导入类
<?php
namespace App\Imports;
use App\Shipment;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
Use Auth;
use App\Settings;
use App\ShipmentTracking;
use App\Alert;
class ShipmentImport implements ToCollection, WithHeadingRow
{
public function __construct($weight_id)
{
$this->weight_id= $weight_id;
}
public function collection(Collection $rows)
{
$user_id = Auth::User()->id;
foreach ($rows as $row)
{
$consign_no = Settings::where('name', 'consign_no')->first()->value;
$increment = $consign_no+1;
$initial = "12".date("y");
$consignment_no1 = $initial.$increment;
$update_setting = Settings::where('name', 'consign_no')->first();
$update_setting->value = $increment;
$update_setting->save();
$shipment = Shipment::create([
'user_id' => $user_id,
'customer_name' => $row['customer_name'],
'customer_address' => $row['customer_address'],
'customer_email' => $row['customer_email'],
'customer_phone' => $row['customer_phone'],
'destination_country' => $row['destination_country'],
'destination_city' => $row['destination_city'],
'service_type' => $row['service_type'],
'tb_date' => $row['tb_date'],
'tb_time' => $row['tb_time'],
'pickup_location' => $row['pickup_address'],
'product_name' => $row['product_name'],
'quantity' => $row['product_quantity'],
'consignment_no' => $consignment_no1,
'weights_id' => $this->weight_id,
'product_value' => $row['product_value'],
'product_reference' => $row['product_reference'],
'remarks' => $row['remarks'],
'status' => 'Booked',
]);
}
}
}
我有 Laravel 版本 7。 我使用的 Excel 文件包是:maatwebsite/excel: 3.1
【问题讨论】:
-
在创建模型之前进行一些验证以检查是否确实设置了键,您可能有一个空白行、隐藏行或类似的事情发生
-
@Ballard 但它在行数超过 5 时有效
-
这并没有改变我所说的,对前 5 行进行一些调试,如果它的 4、3、2,1 等...
-
@Ballard Okay 会检查的
标签: laravel laravel-7 maatwebsite-excel laravel-excel