簡體   English   中英

Laravel 導出:嘗試讀取 null 上的屬性“second_key”

[英]Laravel Export: Attempt to read property "second_key" on null

我需要使用 Laravel Export 導出數據,但代碼返回 ErrorException: Attempt to read property "second_key" on null

我的代碼:

<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class DataExporter extends ExcelExporter implements FromQuery, WithMapping, ShouldAutoSize
{
protected $fileName = 'Export Data.xlsx';
    public function headings(): array
    {
        return [
            'ID',
            'Title',
            'Status',
            'Gender',
            'Data',
        ];
    }
    public function map($data): array
    {
        return [
            $data->id,
            $data->title,
            $data->status,
            $data->gender,
            $data->json_data->second_key, // <-- Here's the error
        ];
    }

}

我試着用這個來檢查:

print_r(json_encode($data->json_data));

這是結果:

{
      "id": 282,
      "second_key": "second_value",
      "third_key": "6200",
      "fourth_key": "0000",
      "fifth_key": 28
}

我也這樣做過:

return [
     $data->id,
     $data->title,
     $data->status,
     $data->gender,
     $data->json_data //Without "second_key"
];

excel 單元格返回相同的結果:

{
      "id": 282,
      "second_key": "second_value",
      "third_key": "6200",
      "fourth_key": "0000",
      "fifth_key": 28
}

正如@dbf在評論部分所說,我必須處理空行。 我在數據庫中檢查了好幾次,也許我錯過了那一行空白。 無論如何,這就是我處理這些值的方式:

if (!isset($data->json_data->second_key)) {
    $second_key = '-';
} else {
    $second_key = $data->json_data->second_key;
}

return [
     $data->id,
     $data->title,
     $data->status,
     $data->gender,
     $second_key
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM