代码之家  ›  专栏  ›  技术社区  ›  user5369932

laravel如何插入多个值

  •  0
  • user5369932  · 技术社区  · 10 年前

    大家好,我是laravel的初学者,我想知道如何将一个多值插入到一个表中,比如,我有一个 订单_明细 我的数据库中的表,它有 order_id、product_id、price和total,

    我想插入一个多值,所以我创建 类型 像这样 可以添加 使用javascript

    <?php for($x = 1;$x <=2; $x++){ ?>
    
      {{ Form::text('', $x]) }}
      {{ Form::text('pj[$x]order_id') }}
      {{ Form::text('pj[$x]product_id) }}
      {{ Form::text('pj[$x]price) }}
      {{ Form::text('pj[$x]total) }}
      {{ Form::submit('insert!') }}
    
    <?php } ?>
    

    然后我在我的 OrderDetailController

    $inputs = Input::get('pj');
    
    if(DB::table('order_detail')->insert($inputs)){
      return Redirect::route('admin.order_detail.index')
                      ->with('message','success');
    }
    return Redirect::back()
             ->with('message','something went wrong')
             ->withInput();
    

    但我只从输入中得到1个值,这是最后一个值

    ps:这是我第一次在这个论坛上提问,所以如果你需要任何信息,请随时问我,请原谅我的英语不好,提前谢谢!

    3 回复  |  直到 10 年前
        1
  •  0
  •   rome 웃    10 年前

    你能打印你的输入吗?我会检查的。 或者尝试以下代码:

    $inputs = Input::get('pj');
    foreach($inputs as $input){
       if(DB::table('order_detail')->insert($input)){}
       else{
          return Redirect::back()
            ->with('message','something went wrong')
            ->withInput();
          }
    }
    Redirect::route('admin.order_detail.index')
                  ->with('message','success');
    
        2
  •  0
  •   Ján Kyselica    10 年前

    首先,代码中有拼写错误,如下所示:

    {{ Form::text('pj[$x]product_id) }}
    

    应该是:

    {{ Form::text('pj[$x]product_id') }}
    

    这将创建文本输入:

    <input name="pj1product_id" type="text">
    

    像这样输入名称,您应该在PHP中解析,但您可以使用表单字段数组。

    未测试示例:

    @for($x = 1;$x <=2; $x++)
       {{ Form::text('', $x) }}
       {{ Form::text('pj[][order_id]') }}
       {{ Form::text('pj[][product_id]') }}
       {{ Form::text('pj[][price]') }}
       {{ Form::text('pj[][total]') }}
    @endfor
    {{ Form::submit('Insert') }}
    

    以及PHP:

    $pj = Input::get('pj');
    foreach($pj as $key=>$order) {
       DB::table('order_detail')->insert($order);
    }
    
        3
  •  0
  •   user5369932 user5369932    10 年前

    谢谢真的谢谢你们俩。 在这里,我将我的代码与两个代码的引用结合起来

    我的表格

    @for($x = 1; $x <=2; $x++)
    
      {{ Form::text('', $x]) }}
      {{ Form::text('pj['. $x .'][order_id]') }}
      {{ Form::text('pj['. $x .'][product_id]') }}
      {{ Form::text('pj['. $x .'][price]') }}
      {{ Form::text('pj['. $x .'][total]') }}
    
    @endfor
    
    {{ Form::submit('insert!') }}
    

    这是我的功能

    $pj = Input::get('pj');
    
    foreach($pj as $order) {
      if(DB::table('order_detail')->insert($order)) {}
      else {
        return Redirect::route('admin.order_detail.index')->with('message','failed');
      }
    }
    
    return Redirect::route('admin.order_detail.index')->with('message','success');