【问题标题】:laravel how to inserting multiple valuelaravel如何插入多个值
【发布时间】:2015-12-21 11:26:51
【问题描述】:

大家好,我是 laravel 的初学者,我想知道如何将多个值插入到表中,例如,我的数据库中有一个 order_detail 表,它有 order_id 、product_id、价格和总计,

我想插入一个多重值,所以我创建 form 像这样 可以使用 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:这是我第一次在这个论坛提问,所以如果您需要任何信息,请随时问我,请原谅我的英语不好,提前谢谢!

【问题讨论】:

  • 虽然我已经尝试了一些代码,但它总是以失败告终,所以到目前为止我可以做到

标签: php arrays laravel laravel-4 crud


【解决方案1】:

谢谢!!真的很感谢你们俩。 在这里,我将我的代码与您的两个代码的参考结合起来

我的表格

@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');

【讨论】:

    【解决方案2】:

    一开始,你的代码有错别字,这个:

    {{ 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】:

      你能打印你的输入吗?我会查一下。 或者试试这个代码:

      $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');
      

      【讨论】:

        猜你喜欢
        • 2019-09-09
        • 2014-08-09
        • 2016-04-03
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 1970-01-01
        相关资源
        最近更新 更多