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 :
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
Have you tried passing a closure to groupBy method? Same as whereHas.
Yes but not worked
I think the problem is morph!
Can you tell what you need that query to result to? Cause you can try something like
Meta::with('orders')->groupBy('value')->get();
Or even better
Meta::with('orders')->where('key', 'gmail')->get();
Just one thing, you should remove that screenshot from your initial post since it looks like real data.
i got this error
there is any wat get metas from Order class and grouping them?
i have many orders that have same meta like gmail
i want grouping them with meta and get orders that have same meta like gmail to use in backpack laravel crud
Just add that relationship and you are all set to go.
Should be something like
public function orders(): MorphTo
{
return $this->morphTo();
}
it works fine but i use this code:
Meta::with('metable')->where('key','gmail')->groupBy('value')->get();
but now how can i limit orders?
for example just order that belongs to specific user or any where closure
i try this but not worked
$this->data['emails'] = Meta::with(['metable' => function($query) {
$query->where('user_id' , 2);
}])->where('key','gmail')->groupBy('value')->get();
and nothing changed
got all orders !
finaly i found the solution
new feature of laravel 5.8 is a closure handled my problem
whereHasMorph()
and this is working code:
$this->data['emails'] = Meta::whereHasMorph('metable' , Order::class , function($query) {
$query->where('user_id' , 2);
})->where('key','gmail')->groupBy('value')->get();
Tnx Every One
Please sign in or create an account to participate in this conversation.