我正在與Laravel第一次合作。我有一個場景,其中包含產品(瓦楞紙箱)的基本細節(如長度,寬度,高度等)的產品表格。產品的一些其他細節使用功能中的基本細節進行計算。Collection-> put()不在Laravel工作5.2
我在控制器代碼如下所示:
控制器:
$products = DB::table('master_products')
->join('part_types', 'master_products.part_type_id', '=', 'part_types.id')
->join('box_types', 'master_products.box_type_id', '=', 'box_types.id')
->select('master_products.*', 'part_types.part_type', 'box_types.box_type')
->get();
/* Calculate Specs and add them to the collection */
foreach ($products as $product) {
$rollSize = $this->calcRollSize($product->height, $product->breadth, $product->ply, $product->part_type_id, $product->box_type_id);
$products->put('roll_size', $rollSize);
}
return view('/layouts/masters/products-master', ['products' => $products]);
查看:
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Sl.No.</th>
<th>Product Code</th>
<th>Part Type</th>
<th>Box Type</th>
<th>Length</th>
<th>Breadth</th>
<th>Height</th>
<th>Ply</th>
<th>Roll Size</th>
<th>A-Base</th>
<th>A-Flute</th>
<th>B-Base</th>
<th>B-Flute</th>
<th>Top</th>
</tr>
</thead>
<tbody>
@foreach($prod_specs as $prod_spec)
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $prod_spec->product_code; ?></td>
<td><?php echo $prod_spec->part_type; ?></td>
<td><?php echo $prod_spec->box_type; ?></td>
<td><?php echo $prod_spec->length; ?></td>
<td><?php echo $prod_spec->breadth; ?></td>
<td><?php echo $prod_spec->height; ?></td>
<td><?php echo $prod_spec->ply; ?></td>
<td><?php echo $prod_spec->roll_size; ?></td>
<td><?php echo $prod_spec->gsm_a_base; ?></td>
<td><?php echo $prod_spec->gsm_a_flute; ?></td>
<td><?php echo $prod_spec->gsm_b_base; ?></td>
<td><?php echo $prod_spec->gsm_b_flute; ?></td>
<td><?php echo $prod_spec->gsm_top; ?></td>
</tr>
<?php $i++; ?>
@endforeach
</tbody>
</table>
我得到這個異常:調用一個成員函數將()放在非對象上
但根據this stackoverflow question的接受的答案它應該工作。我在這裏錯過了什麼?
更新:
試過這種
foreach ($products as $product) {
$rollSize = $this->calcRollSize($product->height, $product->breadth, $product->ply, $product->part_type_id, $product->box_type_id);
$product['roll_size'] = $rollSize;
}
得到一個錯誤Cannot use object of type stdClass as array
噢好吧。我的錯。那麼在那種情況下,我怎樣才能將'roll_size'添加到'$ products'數組中? –
和你在其他數組中添加東西一樣:'$ products ['roll_size'] = $ rollSize' –
'dd($ product)'在你的循環中並且用輸出更新你的問題。還要注意,在這個循環運行之後,將只有'roll_size'的_one_索引。如果您需要一系列捲尺寸,您可能需要重新考慮設計。 –