我被困在图解如何将我的数据阵列存储成一个单个,以便我可以使用eloquent将其插入桌子上。我正在使用javascript来添加动态行。这是JS:

$(function(){
var rowCount = document.getElementById('tblContacts').rows.length - 1 ;
var rowArrayId = rowCount ;

function addRow(){

    $("#tblContacts tbody").append(
        "<tr>"+
        "<td><input type='text' name='product[" + rowArrayId + "][name]' class='form-control'/></td>"+
        "<td><textarea name='product[" + rowArrayId + "][description]' class='form-control' rows='1'></textarea></td>"+
        "<td><input type='text' name='product[" + rowArrayId + "][quantity]' class='form-control'/></td>"+
        "<td><input type='text' name='product[" + rowArrayId + "][price]' class='form-control'/></td>"+
        "<td><button class='btnRemoveRow btn btn-danger'>Remove</button></td>"+
        "</tr>");

    $(".btnRemoveRow").bind("click", removeRow);

rowArrayId = rowArrayId + 1; };


function removeRow(){
    var par = $(this).parent().parent(); //tr
    par.remove();
};
});
.

,这是我的html文件

<tr>
<td><input type='text' name='product[0][name]' class="form-control"/></td>
<td><textarea name='product[0][description]' class="form-control" rows="1"></textarea></td>
<td><input type='text' name='product[0][quantity]' class="form-control"/></td>
<td><input type='text' name='product[0][price]' class="form-control"/></td>
<td><button class="btnRemoveRow btn btn-danger">Remove</button></td>
 </tr>
$(".btnRemoveRow").bind("click", removeRow);
$("#btnAddRow").bind("click", addRow);          
. 当我尝试使用

时,在我的控制器中
$input = Input::get('product');
dd($input);
.

我得到了这些结果:

array (size=3)
0 => 
array (size=4)
  'name' => string 'first product' (length=13)
  'description' => string 'first product description' (length=25)
  'quantity' => string '10' (length=2)
  'price' => string '15' (length=2)
1 => 
array (size=4)
  'name' => string '2nd product ' (length=12)
  'description' => string '2nd product description' (length=23)
  'quantity' => string '20' (length=2)
  'price' => string '20' (length=2)
2 => 
array (size=4)
  'name' => string '3rd product ' (length=12)
  'description' => string '3rd product description' (length=23)
  'quantity' => string '25' (length=2)
  'price' => string '30' (length=2)
.

我从这里学到了它: 从Laravel 4输入生成新数组

我的问题是如何将这些数组放入单个阵列,如此代码

$insert = array();

foreach($tab as $key => $value)
{
$insert[] = array(
    'id_reservation' => $reservation_id,
    'produit_id' => $key,
    'quantite' => $value
);
}

DB::table('products')->insert($insert);
.

我也从这里获取上面的代码: [求助]流利的查询构建器多个插入用foreach

有帮助吗?

解决方案

通过构造关联数组来插入多个值,其中键是列名并且值是值,嗯,值。这不是明显的为什么你被困惑,因为你提供的例子很多是:

$inserts = array();
foreach ( $input as $v ) {
    $inserts[] = array('name' => $v['name'], 'quantity' => $v['quantity']);
}
DB::table('your_table')->insert($inserts);
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top