douque8861 2019-02-21 07:25
浏览 94

Eloquent错误地将多个模型保存到数据库

I have a controller that creates a new model then passes it to the view

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]);
}

I need it to only create one record in the db but it creates 2 records everytime I go to that route.

I have removed the ->save and then no records are inserted into the DB.

Any suggestions?

Edit:

  1. Image of DB entries on the $form->save: SCREENSHOT IMAGE LINK

  2. The DB Schema:

    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();
    });
    
  3. The code that receives the ajax from the sites.fill_site_form view

    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();
    }
    
  4. Front end AJAX code:

        $('#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)
                }
    
            });
        });
    
  • 写回答

1条回答 默认 最新

  • duanluwei9374 2019-02-21 08:16
    关注

    I couldn't get it working with Model::create or Model->save, So I resorted to Model::firstOrCreate which looks more stable, still would like to know why only on that model it creates two entries

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法