无法在Laravel中将Illuminate \ Database \ Eloquent \ Collection类的对象转换为int

时间:2018-08-02 13:15:12

标签: mysql sql laravel laravel-5 eloquent

我有一个名为purchase_details的表,在购买期间,我一次存储许多物品的购买记录。在购买过程中,我还根据购买的商品ID更新商品表列的open_balance,现在在尝试将“商品详情”表数量的值与“ items”表旧的open_balance相加时遇到麻烦-在控制器中,我正在尝试类似的操作-

public function store(Request $request)
{
$grandTotal = $request->input('grand_total');
$paidAmount = $request->input('paid_amount');
$purchase = new Purchase;

$purchase->no          = $request->input('no');
$purchase->purchase_date = Carbon::parse($request->purchase_date)->format('Y-m-d');
$purchase->notes       = $request->input('notes');
$purchase->supplier_id = $request->input('supplier');
$purchase->total_quantity = $request->input('total_quantity');
$purchase->grand_total = $grandTotal;
$purchase->paid_amount = $paidAmount;
$purchase->due_amount  = abs($grandTotal - $paidAmount);
$purchase->save();

$itemDetails = [];
$itemIds = $request->input('itemIds');
$itemQuantities = $request->input('itemQuantities');
$itemPrices = $request->input('itemPrices');
$itemTotals = $request->input('itemTotals');
$orderNotes = $request->input('orderNotes');

foreach ($itemTotals as $key => $total) {
    $itemDetails[] = [
        'item_id' => $itemIds[$key],
        'quantity' => $itemQuantities[$key],
        'unit_price' => $itemPrices[$key],
        'total_price' => $itemTotals[$key],
    ];
    $openingBalance = Item::where('id', $itemIds[$key])->get(['opening_balance']);
    DB::table('items')
                ->where('id', $itemIds[$key])
                ->update(['opening_balance' => $openingBalance + $itemQuantities[$key]]);
}
$purchase->purchaseDetails()->createMany($itemDetails);

return back();
}

1 个答案:

答案 0 :(得分:2)

您将collection用作int,编辑代码:

$openingBalance = Item::select(['opening_balance'])->where('id', $itemIds[$key])->first()->opening_balance;