jonjie
8 months ago

How to use whereHas inside of where?

Posted 8 months ago by jonjie

I'm using laravel v4.2 here. My code returns empty when I'm using it. Please see my code below.

$result = [];

        $targets = CustomerTargetsItem::where('delivery_date', '=', date_format(Carbon::today(), 'm/d/Y'))
        ->whereHas('customerTarget', function($query){
            return $query->where('category_slug', 'scheduled_delivery_of_repaired_t12_48x48_and_euro');
        })
        ->where(function($query){
            return $query->whereHas('replacement', function($query){
                    return $query->where('status', 3)
                    ->whereDate('created_at', '=', Carbon::today());
                })
                ->orWhereHas('transfer', function($query){
                    return $query->where('status', 3)
                        ->whereDate('created_at', '=', Carbon::today());
                });
        })
        ->groupBy('customer_id')
        ->orderBy('delivery_date', 'asc')
        ->select(['customer_id', DB::raw('sum(quantity) AS total')])
        ->get();
        
        foreach($targets as $target){
            $result[] = $target->total;
        }

        dd($result);

Any idea about this?

Please sign in or create an account to participate in this conversation.