首页 > 解决方案 > 如何在数据库laravel中插入数据json?

问题描述

我使用 jquery 和 ajax 来获取数据 json 并将其发送到我的控制器,现在我想将此数据插入到表中,请帮帮我。这是jquery ajax代码:

  $('.add-all').on('click', function() {
        var items = [];
        let valu = $('#datePicker').val();
      $("tr").each(function(i,r){
        if ( i > 0 && $(r).find("input").first().prop("checked"))
        {  
          items.push({"matricule": r.cells[3].innerText, "salaire": r.cells[5].innerText, "date" : valu })
              }
                                      });
//ajax
$.ajax({ 
        method      : 'POST', 
        url       : 'mois', 
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data      : {"items":items}, // pass in json format 
        success   : function(data) {
            console.log(data);
        },
        error : function(err){
            console.log(err)
        }
    });

//fin ajax 
      });  

控制器 :

   public function addMultiple(Request $request){
      $data = $request->only('datep','salaire','matricule');
      $pointage['data'] = json_encode($data);
      Pointage::insert($pointage);

  }

我得到:

 data: {…}
    items: (3) […]
    0: Object { matricule: "1", salaire: "6000", date: "2019-06-23"}
    1: Object { matricule: "2", salaire: "5000", date: "2019-06-23"}
    2: Object { matricule: "3", salaire: "7000", date: "2019-06-23" }
    length: 3
    <prototype>: Array [
    <prototype>: {…

型号积分:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Pointage extends Model
{
    //
}

表积分

 public function up()
    {
        Schema::create('pointages', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('matricule');
            $table->date('datep');
            $table->double('nbrj');
            $table->double('prime');
            $table->double('solde');
            $table->timestamps();
        });
    }

标签: ajaxlaravel

解决方案


推荐阅读