Search code examples
laravelwherehas

How To Use groupBy in whereHas laravel


i am using Metable in my project for creating meta for orders
but i have one problem
i want group orders that have same email
this is metable table image : image 1 image 2

i need code like this can work :)

Order::whereHas( 'meta', function($query) {
        $query->where("key" , "gmail");
})->groupBy('meta.value')->get();

and this is meta relation that called by trait 'use Metable' in Order Model:

public function meta(): MorphMany
{
    return $this->morphMany($this->getMetaClassName(), 'metable');
}

Thanks


Solution

  • This query may work, we start querying from the Meta model:

    Meta::with('metable')
        ->whereHasMorph('metable', Order::class)
        ->where('key', 'gmail')
        ->get()
        ->groupBy('value')
        ->map(function ($metaCollection) {
            return $metaCollection->map->metable->unique('id');
        });