我正在使用Laravel 5.7.*
。
我有form
,其中有很多formItems
,就像form hasMany formItems
和formItems belongsTo form
,但我希望它们之间有一个if
,如果用户不想要仅在formItems
中添加form
个DB
数据存储,并且如果用户想在formItems
中添加DB
两个数据存储,现在,它存储两个数据在DB
中,但是如果用户不希望使用formItems
,我不会如何存储它。
这是我的FormController
store method()
:
public function store(Request $request)
{
//SUBMITTING FORM DATA
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_name' => $request['user_name'],
]);
//SUBMITTING FORMITEMS DATA
$form_items = [];
foreach($request['formItems'] as $form_item) {
$form_items[] = new FormItem([
'form_id' => $form->id,
'family_name' => $form_item ['family_name'],
'family_phone' => $form_item ['family_phone'],
]);
}
$form->formItems()->saveMany($form_items);
}
答案 0 :(得分:0)
您可以在表单上有一个复选框,询问用户是否也要保存表单项。
merge(source1$, source2$).pipe(take(1))
,然后在您的控制器中,您可以执行以下操作:
<input type="checkbox" name="save-form-items" value="true" id="save-form-items">
<label for="save-form-items"> Do you want to save form items?</label>
答案 1 :(得分:0)
您可以做到
public function store(Request $request)
{
//SUBMITTING FORM DATA
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_name' => $request['user_name'],
]);
$form_items = [];
foreach($request['formItems'] as $form_item) {
// when the user enter $form_item ['family_name'] && $form_item ['family_phone'] store the FormItem
// or $form_item ['family_name'] || $form_item ['family_phone']
// depending if both are required or not
if($form_item ['family_name'] && $form_item ['family_phone']){
$form_items[] = new FormItem([
'form_id' => $form->id,
'family_name' => $form_item ['family_name'],
'family_phone' => $form_item ['family_phone'],
]);
}
}
$form->formItems()->saveMany($form_items);
}