php 如何在Laravel中存储数组?

vd2z7a6w  于 2023-05-05  发布在  PHP
关注(0)|答案(3)|浏览(108)

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

{!!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()!!}

当我点击一个复选框时,它会进入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);

   }
}

它不起作用,但我如何解决这个问题?

mwg9r5ms

mwg9r5ms1#

试试这个代码

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

你也可以使用

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

这是执行此操作的更好方法,因为它将与数据库交互一次。

xwbd5t1u

xwbd5t1u2#

也可以创建模型的新示例来存储值。
示例:

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

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

    $reserved->save();
}
zqry0prt

zqry0prt3#

$input = $request->all();
        
    $invoice = Invoice::create($input);
    
    foreach($input['products'] as $key => $value){            
        $product['product_id'] = $value['product_id'];
        $product['amount'] = $value['amount']; 
        $product['invoice_id'] = $invoice->id;
        InvoiceProducts::create($product);
    }

    return redirect()->route('invoices.index')->with('success', 'Invoice Added Successfully');

}

相关问题