【发布时间】:2019-02-21 07:25:24
【问题描述】:
我有一个控制器,它创建一个新模型然后将它传递给视图
public function fill_site_form($id, $step_id, $form_id){
$form = new FormEntry();
$form->site_id = $id;
$form->form_id = $form_id;
$form->step_id = $step_id;
$form->entry_json = Form::find($form_id)->form_json;
$form->save();
return view('sites.fill_site_form', ['form' => $form]);
}
我只需要它在数据库中创建一条记录,但每次我去那条路线时它都会创建两条记录。
我已经删除了->保存,然后没有记录插入到数据库中。
有什么建议吗?
编辑:
$form->save 上的 DB 条目图像: SCREENSHOT IMAGE LINK
-
数据库架构:
Schema::create('form_entries', function (Blueprint $table) { $table->increments('id'); $table->integer('site_id'); $table->integer('form_id'); $table->integer('step_id'); $table->text('entry_json', 600000); $table->timestamps(); }); -
从 sites.fill_site_form 视图接收 ajax 的代码
public function update_site_ajax($id, Request $request){ $entry = FormEntry::find($id); $entry->entry_json = json_encode($request->form_json); $entry->save(); return $request->all(); } -
前端AJAX代码:
$('#submit_button').click((e)=>{ $.ajax({ type:'PATCH', url:'/site/' + document.getElementById('form_id').value, data: {'form_json' : renderer.userData}, success:function(data){ $.notify("Form successfully Updated!", { position:"top center", className: 'success' } ); console.log('Response: ', data) } }); });
【问题讨论】:
-
请问您可以显示您的
FormEntity模型的内容吗?另外,您是否为模型或其任何关系设置了任何事件侦听器? -
还是从 AJAX 发送相同的数据?
-
@RossWilson 我已经编辑了答案,向您展示了 FormEntry 模型的内容和架构!够了吗
-
@BILALMALIK 该视图确实通过 ajax 发布数据,在编辑 3 中,我添加了接收 ajax 的代码。虽然这两个条目都是在渲染视图时添加的
-
@elfif 感谢您提供很棒的工具建议!它显示查询只运行了一次,但数据库中仍有两个条目。我尝试使用 FormEntry:create() 但它也创建了两个条目。我求助于使用 FormEntry: firstOrCreate() 它只给我一个条目和它的稳定。感谢您的时间!
标签: php laravel eloquent model