lundi 17 août 2020

Compare cart products with available deals - Laravel

I'm adding deals to my custom ecommerce. That means admin can create deals and specify for which products / categories / brands is the deal valid. For example admin can create deal 2+1 but just for the Category_01 or he can create a deal - buy products at least for $100 in Category_01 and get one free. I have created table with deals and pivot tables for products/categories/brands. Everything works fine until now. When user has products in his cart I need to find the deals which meet cart content. I was trying something like this:

$productIds = array_unique($cartProducts->pluck('product_id')->toArray());
$categoryIds = ShopProductCategoryPivot::whereIn('product_id', $productIds)->pluck('category_id')->toArray();
$brandIds = array_unique($cartProducts->pluck('product.brand_id')->toArray());

$deals = ShopProductDeal::published()
                        ->whereHas('productsPivot', function($q) use ($productIds) {
                            $q->whereIn('product_id', $productIds);
                        })->orWhereHas('categoriesPivot', function($q) use ($categoryIds) {
                            $q->whereIn('category_id', $categoryIds);
                        })->orWhereHas('brandsPivot', function($q) use ($brandIds) {
                            $q->whereIn('brand_id', $brandIds);
                        })->with(['lang', 'products', 'categories', 'brands'])
                        ->get();

This code works but it is not enough. I need to compare if products count/sum(price) meets the conditions defined. I was thinking about using

whereHas(function(){...}, '=', $required_count) 

but I don't know what number is $required_count. Do you have any idea how to solve this?

Aucun commentaire:

Enregistrer un commentaire