Home > Software engineering >  How I can update product items of an order where the product is discountable?
How I can update product items of an order where the product is discountable?

Time:12-24

the Order model hasmany items relation and the item belongsto a product;

the items table is: id - order_id - product_id - coupon_id

the coupon column is nullable and I want to add the coupon_id to products that are discountable. the discountable property in the products table is boolean.

this code update all coupn_id:

 $order->items()->update([
   "coupen_id" => $coupen->id,
]);

Here I can get those products:

      $items = $order->items;
      $discountable_products = $items->map(function ($item) {
            return $item->product;
        })->filter(function ($item) {
            return $item->discount === 1;
        });

also, I have tried:

        if ($coupon) {
            foreach ($order->items as $item) {
                foreach ($item->product as $product)
                    if ($product->discount === 1) {
                        $order->items()->update([
                            "coupen_id" => $coupen->id,
                        ]);
                    }
            }

        }

and it doesn't work.

How I must update the coupon_id of products by $order->items()->update([]) that are discountable.

CodePudding user response:

I think you can skip loop with whereIn:

//Pluck product ids from collection
$product_ids_array = $discountable_products->pluck('id')->toArray();

//if $coupon->id is constant
$order->items()->whereIn('product_id', $product_ids_array )->update([
            "coupen_id" => $coupon->id,
        ]);

CodePudding user response:

    if ($coupon) {
        foreach ($discountable_products as $product) {
            $order->items()->where('product_id', $product->id)->update([
                "coupen_id" => $coupon->id,
            ]);
        }
    }
  • Related