从 Angular 发送数据时,laravel 中的日期时间格式无效

谁能帮助我如何解决这个问题?我有一个来自 Angular 的请求数据,已将其传递到 Laravel 后端,以便一次插入多行。但我得到了以下错误。我尝试在 Mysql 中运行以下查询,它在那里工作正常,但不是从 laravel 运行。


我怎样才能解决这个问题??


从 Angular (API) 请求数据:


[

  {

    "customer_id": 3,

    "check_in_date": "2020-07-30T00:00:00.000Z",

    "check_out_date": "2020-07-31T00:00:00.000Z",

    "room_id": 2

  },

  {

    "customer_id": 3,

    "check_in_date": "2020-07-29T00:00:00.000Z",

    "check_out_date": "2020-07-31T00:00:00.000Z",

    "room_id": 3

  }

]

迁移表


public function up()

{

    Schema::create('reservations', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->unsignedBigInteger('room_id');

        $table->foreign('room_id')->references('id')->on('rooms');

        $table->unsignedBigInteger('customer_id');

        $table->foreign('customer_id')->references('id')->on('customers');

        $table->unsignedBigInteger('booking_id')->nullable();

        $table->foreign('booking_id')->references('id')->on('bookings');

        $table->dateTime('check_in_date');

        $table->dateTime('check_out_date');

        $table->timestamps();

    });

}

预订控制员:


public function store(Request $request)

{

    $reservation = Reservation::insert($request->all());

    

    return $this->jsonResponse(true, 'Reservation has been created successfully.', $reservation);

}



private function jsonResponse($success = false, $message = '', $data = null)

{

    return response()->json([

        'success' => $success,

        'message' => $message,

        'data' => $data

    ]);

}

错误:


 "message": "SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2020-07- 

 29T00:00:00.000Z' for column 'check_in_date' at row 1 


 (SQL: insert into `reservations` (`check_in_date`, `check_out_date`, `customer_id`, `room_id`)


 values (2020-07-30T00:00:00.000Z, 2020-07-31T00:00:00.000Z, 3, 2),

        (2020-07-29T00:00:00.000Z, 2020- 07-31T00:00:00.000Z, 3, 3))",

 "exception": "Illuminate\\Database\\QueryException",


慕的地8271018
浏览 79回答 1
1回答

蝴蝶不菲

日期的格式错误,尝试使用 转换它们Carbon,它应该自动序列化为您的 DBMS 想要的正确形式:use Carbon\Carbon;...function store(Request $request){    $all = array_map(function($el){        $el->check_in_date = Carbon::createFromFormat('Y-m-d\TH:i:s+', $el->check_in_date);        $el->check_out_date = Carbon::createFromFormat('Y-m-d\TH:i:s+', $el->check_out_date);        return $el;    }, $request->all());    $reservation = Reservation::insert($all);        return $this->jsonResponse(true, 'Reservation has been created successfully.', $reservation);}编辑:似乎访问对象字段存在一些问题,使用$el['check_in_date']而不是解决$el->check_in_date
打开App,查看更多内容
随时随地看视频慕课网APP