【问题标题】:Adding multiple values into Session to insert in a pivot table将多个值添加到 Session 以插入数据透视表
【发布时间】:2014-07-11 22:24:05
【问题描述】:

我有三个表 delivery-request_item、items 和一个数据透视表 delivery-request_item。在我的 create.blade.php 中,我有一个按钮,它将添加用户选择的相应数量的项目之一。

我的解决方案是将商品和数量放到 Session 中。现在我的问题是我只能创建一个记录,如果我决定添加另一个项目,前一个项目会被覆盖。

create.blade.php

{{Form::open(array('method'=>'POST','url'=>'delivery-requests'))}}
{{Form::text('requested_by', Auth::user()->email)}}

<div>
    {{Form::label('Shows Items from table')}}   
    {{Form::select('item_id', $items)}}

    {{Form::label('Quantity')}}
    {{Form::text('item_quantity')}}

    {{Form::submit('add item',array('name'=>'addItem'))}}
    {{Form::submit('remove item', array('name' => 'removeItem'))}}
</div>
<hr>
<div>
    <table>
        <theader>
            <tr>
               <td>ITEM NAME</td>
               <td>QUANTITY</td>
            </tr>
        </theader>

            <!-- loop through all added items and display here -->

        @if(Session::has('item_id'))
        <h1>{{ Session::get('item_id') }}</h1>
        @endif
        @if(Session::has('item_quantity'))
        <h1>{{ Session::get('item_quantity')}}</h1>
        @endif
    </table>
</div>
{{Form::submit('submit', array('name' => 'submit'))}}
{{Form::close()}}

DeliveryRequestsController@Store

if(Input::has('addItem'))
{
  Session::flash('item_id', Input::get('item_id'));
  Session::flash('item_quantity', Input::get('item_quantity'));
  $data =  Session::all();
  $item = Item::lists('item_name','id');
  return View::make('test')->with('data',$data)->with('items',$item);   
}

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    两件事。

    1. 您需要将会话设为数组,否则您将始终覆盖。

    2. 您无需使用flash(),因为一旦发出另一个请求,此数据就会被删除,这就是闪存数据,即持续到下一个请求的数据。

    试试这个:

    if(Input::has('addItem')) {
        if(Session::has('items')) {
            Session::push('items', [
                'id'    => Input::get('item_id'),
                'qty'   => Input::get('item_quantity')
            ]);
        } else {
            Session::put('items', [
                'id'    => Input::get('item_id'),
                'qty'   => Input::get('item_quantity')
            ]);
        }
    }
    

    Session::push() 与存储在会话中的数组一起使用,如果 Session::put() 不存在,则显然会使用它。

    请记住,这些数据将保持不变,并且需要在某些情况下清除,例如在您完成后。

    有关会话的更多信息,请阅读:http://laravel.com/docs/session

    【讨论】:

    • 我注意到要添加的第一项没有数组索引。你可以看到here 那个item_id:1。但随后添加的每个后续项目都会获得“1”:数组索引。执行print_r() 会将其显示为Array ( [item_id] =&gt; 1 [item_quantity] =&gt; 12 [0] =&gt; Array ( [item_id] =&gt; 2 [item_quantity] =&gt; 22 ) [1] =&gt; Array ( [item_id] =&gt; 3 [item_quantity] =&gt; 33 ) )
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多