要在 laravel 內將 json 資料批次匯入資料庫,可以先將要匯入的 json 檔放到 storage 資料夾,然後把 json 讀入後,再透過迴圈寫入資料庫。
Route::get("/insertData", function(){
$json = file_get_contents(storage_path('data.json'));
$objs = json_decode($json,true);
foreach($objs as $value){
$data["id"]=null;
$data['year']=$value["年份"];
$data['name']=$value["獎名"];
$data['online']=1;
$data['item']=$value["獎項"];
$data['subject']=$value["得獎題目"];
$data['people']=$value["得獎者"];
$newData =Modal::firstOrNew(['id'=>$data['id']],$data);
if(!$newData->wasRecentlyCreated){
$newData->fill($data);
}
$newData->save();
}
});
其中如果遇到欄位名稱不一樣,就像上面這樣設定好欄位,再透過 model 輸入即可。