Laravel在邮递员中创建一个数组并保存在数据库中

时间:2019-03-19 14:29:31

标签: php laravel postman

在这种情况下,我遇到了麻烦。 这就是我在邮递员中展示的 enter image description here

控制器

this.getSupportActionBar().hide();
  

我陷入了for循环。我该如何处理这种情况?

这就是我在数据库中得到的 enter image description here

2 个答案:

答案 0 :(得分:1)

Problem

I don't know how your code works, because this for ( $times as $time) is not how for works.

Here is a explanation on for https://secure.php.net/manual/pt_BR/control-structures.for.php

Solution

The as on the for make me think your trying to use the foreach. And here is how it works:

foreach( $times as $time) the $time is already a single record from the array

So when you do a foreach this is how it should look:

foreach ( $times as $time){
    $new_time = new TimeParameter();
    $new_time->id_parameter = $parameters->id;
    $new_time->time = $time->time;
    $new_time->hour = $time->hour;
    $new_time->save();
}

答案 1 :(得分:1)

This is because of how your key's are named. time[0].time is not valid and maybe it is reading it to time[0] only. Which is why you are only getting the hours.

time[0].time = 'morning';
time[0].hour = '10:00';

- then it will not count the .time or the .hour because that is not valid. then it would only make it time[0] which then explains why you are only getting the hours.


With the changes on the postman data that I asked you to do. You can try this solution.

public function index(Request $request)
{
 $user =  Auth::guard('api');


    if ($user)
    {
        $parameters=new UserParameters();
        $parameters->id_user=Auth::guard('api')->id();
        $parameters->day=$request->day;

        if($parameters->save())
        {
            $data= $request->all();

            foreach ( $data['times'] as $time)
            {
                $new_time = new TimeParameter();
                $new_time->id_parameter = $parameters->id;
                $new_time->time = $time[0];
                $new_time->hour = $time[1];
                $new_time->save();
            }

            return response()->json(['true' => false, 'message' => 'Saved!']);

        }


    }

    else
    {

        return response()->json(['error' => false, 'message' => 'User not found!']);

    }

}