【问题标题】:Increment product quantity in Order controller PHP Laravel 5.7在订单控制器 PHP Laravel 5.7 中增加产品数量
【发布时间】:2020-09-15 03:28:49
【问题描述】:

我可以在 Laravel 的项目中使用增量吗,我打算在商店中使用它并更新控制器?

我尝试在控制器中存储数据、处理产品、订单和订单详细信息模型时进行更新。

这是我到目前为止所得到的:

App\OrderController

public function store(Request $request)
    {
        $order = Order::create($request->all());
        
        $products = $request->input('products', []);
        $quantities = $request->input('quantities', []);
        for ($product=0; $product < count($products); $product++) {
            if ($products[$product] != '') {
                $order->products()->attach($products[$product], ['quantity' => $quantities[$product]]);
            Product::where('id', $products[$products])->increment('qty',$quantities[$product]); 
            }
        }
    
        return redirect()->route('orders.index');
    }

所以这行是问题所在。我们可以在 store 函数上做这样的增量吗?

产品::where('id', $products[$products])->increment('qty',$quantities[$product]);

我的意思是,我应该在收到订单后增加产品的数量吧?

我没有成功,而是收到如下错误消息:

ErrorException (E_WARNING) 非法偏移类型

我太难了。请帮忙。

【问题讨论】:

  • 不,它仍然说非法

标签: php mysql database laravel


【解决方案1】:

您正在尝试使用他自己作为索引来访问数组。应该是$products[$product],而不是$products[$products]

public function store(Request $request)
{
    $order = Order::create($request->all());
    
    $products = $request->input('products', []);
    $quantities = $request->input('quantities', []);

    for ($product = 0; $product < count($products); $product++)
    {
        if ($products[$product] != '')
        {
            $order->products()->attach($products[$product], ['quantity' => $quantities[$product]]);

            // $products[$product], without the 's'
            Product::where('id', $products[$product])->increment('qty',$quantities[$product]); 
        }
    }

    return redirect()->route('orders.index');
}

【讨论】:

  • 该死的,我是。这是.. 错字杀了我。
  • 每个人都会遇到这种情况!呵呵。有时最好为索引使用不同的名称。在这种情况下,$p$productIndex 会阻止你犯这个错误。
猜你喜欢
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多