【发布时间】:2017-10-05 11:26:18
【问题描述】:
请就我的代码如何正常工作给我一些建议。我有一个循环,它为我提供了一个 id 和数量,以便将每个循环更新到我的数据库中。
但是当我将它传递给我的私有函数并尝试执行它时出现错误。 我只是 PHP/Laravel 的初学者。 这是我的完整代码:
public function updateProduct(Request $request) {
$ids = array();
foreach ($request->products as $ship_id) {
$product_id = DB::table('shipping_products')->select('product_id','quantity')
->where(['shipping_products.shipping_id'=>$ship_id])
->get();
array_push($ids,$product_id);
}
foreach ($ids as $value) {
foreach ($value as $update) {
$this->updateProductQty($update->product_id,$update->quantity);
}
}
}
private function updateProductQty($product_id, $quantity_order) {
$qty = DB::table('products')->select('quantity')
->where(['products.product_id'=>$product_id])
->get();
$updateTotalQty = $qty - $quantity_order;
DB::table('products')
->where('product_id', $product_id)
->update(array(
'quantity' => $updateTotalQty
));
}
我在这行中有一个错误:
$this->updateProductQty($update->product_id,$update->quantity);
它显示错误消息:
Object of class Illuminate\Support\Collection could not be converted to int
【问题讨论】:
-
products和quantity的声明类型是什么?我认为products是CollectionType -
@YaatSuka 感谢您的快速回复。这是 {#300 ▼ +"product_id": 1 +"quantity": 1 } 当 i dd($update) 在 foreach 中时
-
$updateTotalQty的值是多少? -
私有函数 updateProductQty($product_id, $quantity_order) 它是一个函数,我想要的只是每次 foreach 循环获取数据时从数据库更新我的数据
-
对不起,我在这一行谈到了变量:
$updateTotalQty = $qty - $quantity_order;
标签: php laravel sql-update laravel-5.4 private-functions