试图在Laravel中发布一个对象数组.ErrorException:从文件中的空值创建默认对象



我正试图发送一个POST请求,其中包含如下数据集:

[
{
"Course_Code":"CIS341",
"Start_Date":"2020-08-22",
"End_Date":"2020-12-02",
"CRN":345627,
"CWID":"C38475920",
"Date_Registered":"2020-04-02"
},
{
"Course_Code":"CIS341",
"Start_Date":"2020-08-22",
"End_Date":"2020-12-02",
"CRN":456392,
"CWID":"C38475920",
"Date_Registered":"2020-04-02"
},
{
"Course_Code":"CIS341",
"Start_Date":"2020-08-22",
"End_Date":"2020-12-02",
"CRN":562940,
"CWID":"C38475920",
"Date_Registered":"2020-04-02"
}
]

但我只想将每个对象的CRN、CWID、Date_Registered插入到我的final_schedule表中:

protected $table ="final_schedule";
public $timestamps = false;
protected $fillable = [
'CWID',
'CRN',
'Date_Registered'
];

这是我正在使用的插入函数:

public function insert(Request $request){
$CWID->CWID = $request->input('CWID');
$CRN->CRN = $request->input('CRN');
$Date_Registered->Date_Registered = $request->input('Date_Registered');
$items = array('CWID'=>$CWID, 'CRN'=>$CRN, 'Date_Registered'=>$Date_Registered);
finalScheduleModel::insert($items);
}

当我在poster中测试这个插入函数时,它给出了错误:ErrorException: Creating default object from empty value in file错误指向的行是函数的第一行$CWID->CWID = $request->input('CWID');我试着用很多不同的方法编写这个函数,但总是会出现同样的错误。它从不读取任何发送过来的数据。它可能会说类似于试图将值CWID、CRN、Date_Registered(?,?,?(插入final_schedule。

试试这个,看看它是否适合你。

public function insert(Request $request){
$array = [];
foreach (request()->all() as $value) {
array_push($array, ['CWID' => $value['CWID'], 'CRN' => $value['CRN'], 'Date_Registered' => $value['Date_Registered']]);
}
DB::table('final_schedule')->insert($array);
}

最新更新