PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 13, 2022

[FIXED] How I can update product items of an order where the product is discountable?

 January 13, 2022     laravel     No comments   

Issue

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.


Solution

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,
        ]);


Answered By - Faizan Ali
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing