如何在 Laravel 中存储数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51329267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:53:59  来源:igfitidea点击:

How to store array in Laravel?

phparrayslaravelstore

提问by csow

There are two mysql tables 1.seats (id,number), 2.reservedseats(id,seat_id,sceering_id). I show all the seats of a specific sceering as checkboxes in show.blade:

有两个mysql表1.seats(id,number), 2.reservedseats(id,seat_id,sceering_id)。我在 show.blade 中将特定座位的所有座位显示为复选框:

{!!Form::model($screening,['method'=>'post', 'action'=> 
['ReserveController@store',$screening->auditorium->id]])!!}

<input type="hidden" name="screening_id" value="{{$screening->id}}">

@foreach($seats as $seat)

<label class="checkbox-inline">

{!!Form::checkbox('seat_id[]',$seat->id,null)!!} Number: {{$seat->number}}  

</label>

@endforeach

<div class='form-group'>

{!!Form::submit('Create Post',['class'=>'btn btn-primary '])!!}

</div>

{!!Form::close()!!}

When I click a checkbox it goes the the seat_id[] array. So I send a hidden input and an array with the seat_ids then I want to store in the reservedseats Mysql table. But in the store controller I have the problem. I'm trying something like:

当我点击一个复选框时,它会进入seat_id[] 数组。所以我发送一个隐藏的输入和一个带有seat_ids的数组,然后我想存储在reservedseats Mysql表中。但是在商店控制器中我遇到了问题。我正在尝试类似的东西:

public function store(Request $request){

 $screening_id = $request->screening_id;

 $seat_ids = $request->seat_id;

  foreach($seat_ids as $seat_id){

    Seatreserved::create($seat_id,$screening_id);

   }
}

So it not working but how can I solve that?

所以它不起作用,但我该如何解决?

采纳答案by Davit

Try this code

试试这个代码

public function store(Request $request)
{
    $screening_id = $request->screening_id;
    $seat_ids = $request->seat_id;

    foreach($seat_ids as $seat_id) {
        Seatreserved::create([
            'seat_id' => $seat_id,
            'screening_id' => $screening_id
        ]);
    }
}

Also you can use

你也可以使用

public function store(Request $request)
{
    $screening_id = $request->screening_id;
    $seat_ids = $request->seat_id;

    $data = [];
    foreach($seat_ids as $seat_id) {
        $data[] = [
            'seat_id' => $seat_id,
            'screening_id' => $screening_id
        ];
    }
    Seatreserved::insert($data);
}

回答by JPark

You can also create a new instance of your model to store values.

您还可以创建模型的新实例来存储值。

Example:

例子:

foreach($seat_ids as $seat_id) {
    $reserved = new Seatreserved();

    $reserved->seat_id = $seat_id;
    $reserved->screening_id = $screening_id;

    $reserved->save();
}