我的表单数据正在返回此json文件,我必须将其存储为数据库中的多行。
JSON
{
"name": john,
"department" : "IT"
"type" : ['annual', 'private'],
"from_date" : ['2020-09-09', '2020-10-08'],
"to_date" : ['2020-09-12', '2020-10-15'],
"hours" : ['06','09'],
}
我想使用laravel将其存储在数据库中,并且输出应该是
id name department type from_date to_date hours
1 John IT annual 2020-09-09 2020-10-08 06
2 John IT Private 2020-09-12 2020-10-15 09
这是我的laravel代码,我尝试过但不能正常工作,请我需要帮助,我是laravel的新手。谢谢
function getLeave(Request $request){
$leaveInfo = new LeaveTable();
$leaveInfo->name = $request->name;
$leaveInfo->department = $request->department;
if(count($leaveInfo->type >= 1)){
for( $i = 0; $i < count($leaveInfo->type); $i++){
$leaveInfo->type = $request->type[$i];
}
}
if(count($leaveInfo->date_from >= 1)){
for( $i = 0; $i < count($leaveInfo->date_from); $i++)
$leaveInfo->date_from = $request->date_from[$i];
}
}
if(count($leaveInfo->date_to >= 1)){
for( $i = 0; $i < count($leaveInfo->date_to); $i++)
$leaveInfo->date_to = $request->date_to[$i];
}
}
if(count($leaveInfo->hours >= 1)){
for( $i = 0; $i < count($leaveInfo->hours); $i++){
$leaveInfo->hours = $request->hours[$i];
}
}
$leaveInfo->save();
}
答案 0 :(得分:1)
要实现此目的,您需要为“类型”,“ from_date”,“ to_date”,“小时”列创建 text 列。
在迁移中
$table->text('type');
$table->text('from_date');
$table->text('to_date');
$table->text('hours');
然后在模式中,您需要将这些列添加到 casts 数组中。
在模式中
protected $casts = [
'type' => 'array',
'from_date' => 'array',
'to_date' => 'array',
'hours' => 'array',
];
然后在控制器中,这很容易。
在控制器中
$leaveInfo = new LeaveTable();
$leaveInfo->name = request->name;
$leaveInfo->department = request->department;
$leaveInfo->type = request->type;
$leaveInfo->from_date = request->from_date;
$leaveInfo->to_date => request->to_date;
$leaveInfo->hours => request->hours;
$leaveInfo->save();
旁注
LeaveTable::create([
'name' => request('name'),
'department' => request('department'),
'type' => request('type'),
'from_date' => request('from_date'),
'to_date' => request('to_date'),
'hours' => request('hours'),
]);