我遇到了这个问题,因为我的循环只停留在表格的第一行。每个客户都有一套预算用于购买产品,如果数量不等于0,则每周重置一次以购买商品。管理员是可以处理客户订单的人。客户表中的预算= 1000。然后customer_product表具有客户要购买的产品数量。例如,product_id = 1的价格为20,其数量为10,因此20 x 10 = 200.预算将扣除200,剩余预算在循环第一行后将为800。现在我想继续使用剩余的800预算而不是1000预算来循环第二行。只要他仍有预算,它就会继续循环。
数据库表
customer
id | name | budget
customer_product
product_id | cus_id | qty | status
products
id | name | price
控制器
public function processOrder($id)
{
$customers = Customer::find($id);
foreach ($customers->products as $product)
{
$status = $product->pivot->status;
$budget = $product-budget;
$price = $product->price;
$qty = $product->pivot->qty;
if ($status == 1) {
$i = $qty;
for ($i; $i > 0; $i--) {
if ($budget < 1) {
break;
} else {
$budget-=$price;
}
}
};
echo "Status 0";
}
}
路线
Route::get('processOrder/{id}', ['as' => 'processOrder',
'uses' => 'AdminController@processOrder']);
我可以处理表格的第一行,当它与我的for循环达到0时,它停在那里并且不会继续处理下一行,即使他的预算仍足以购买来自下一行。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
你正在强制循环在第一个索引处打破
echo "Status 0"; break;
最后删除break;
。
更新
foreach($customers->products as $product){
$status = $product->pivot->status;
$budget = $product-budget;
$price = $product->price;
$qty = $product->pivot->qty;
if($status == 1){
do {
if($budget < 1) break;
$budget -=$price;
} while ($qty != 0);
}
}
答案 1 :(得分:0)
您应该在进入循环之前保存客户的预算,然后在迭代产品时更新它。
public function processOrder($id)
{
$customer = Customer::find($id);
$remainingBudget = $customer->budget;
foreach ($customer->products as $product) {
// Calculate the total price to get the desired qty of product
$cost = $product->price * $product->pivot->qty;
// If we have enough remaining budget go ahead with the purchase
if ($product->pivot->status == 1 && $remainingBudget >= $cost) {
// Decrease the remaining budget
$remainingBudget -= $cost;
}
}
}