导入时未定义 offset:1 laravel excel

Undefinde offset:1 when importing laravel excel

这是我的代码造成的麻烦,

$cust = Customer::where('name', '=', $data[$i][0]['customer_name'])
    ->pluck('customer_id')[0];

这个用于在我执行商店到销售订单时获取客户 ID

$sales = array(
       'customer_id' => Customer::where('name', '=', $data[$i][0]['customer_name'])->pluck('customer_id')[0],
       'logistics_id' => Logistic::where('logistics_name', '=', $data[$i][0]['logistics'])->pluck('logistics_id')[0],
       'subtotal' => $data[$i][0]['subtotal_rp'],
       'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
       'discount_code' => 0,
       'date_of_sales' => $data[$i][0]['date'],
       'grand_total' => $data[$i][0]['grand_total_rp'],
       'tax' => $data[$i][0]['tax_rp'],
       'status' => $data[$i][0]['status'],
       'discount_amount' => $data[$i][0]['discount_amount_rp']
);
$store_so = SalesOrder::create($sales);

但是,当我这样做时 dd(),我得到了正确的数据

首先,您需要检查 $data 变量 returns 的数据是否符合您的预期。

dd($data);

接下来,需要检查$data数组的元素个数是否符合$total_data

dd(count($data) == $total_data));

所以基本上,你只需要给出条件或try-catch(推荐):

if (isset($data[$i][0])) {
    $customer = Customer::where('name', $data[$i][0]['customer_name'])->first();
    $logistic = Logistic::where('logistics_name', $data[$i][0]['logistics'])->first();

    if(!$customer){
        dd('No customer found!');
    }

    if(!$logistic){
        dd('No logistic found!');
    }

    $sales = [
        'customer_id'     => $customer->customer_id,
        'logistics_id'    => $logistic->logistics_id,
        'subtotal'        => $data[$i][0]['subtotal_rp'],
        'shipping_cost'   => $data[$i][0]['shipping_cost_rp'],
        'discount_code'   => 0,
        'date_of_sales'   => $data[$i][0]['date'],
        'grand_total'     => $data[$i][0]['grand_total_rp'],
        'tax'             => $data[$i][0]['tax_rp'],
        'status'          => $data[$i][0]['status'],
        'discount_amount' => $data[$i][0]['discount_amount_rp'],
    ];
    $store_so = SalesOrder::create($sales);
}
else{
    dd('No $data[$i][0] found!');
}

PS :我建议使用 first() 方法而不是 pluck('customer_id')[0]

看来你需要从 customer_name 得到一个 customer_id。 尽量让一切变得简单:

$sales = array(
       'customer_id' => Customer::where('name', $data[$i][0]['customer_name'])->first()->id,
       ...
);