Reputation: 57
this is the first question I post on this site, hope you can help me!
I have a fragment of code like this in my blade as below.
@foreach($user->orders as $order)
@foreach($order->orderdaytimes as $orderdaytime)
@foreach($orderdaytime->stores as $orderdaytimestore)
@if($orderdaytime->date == $day && $orderdaytimestore->id == $store->id)
The eloquent relationship is as below: - User has many orders - order has many orderdaytimes - orderdaytimes belongs to many stores - Store belongs to many orderdaytimes
as you can see in the code, i needed to loop through all these levels to find out whether there's record in orderdaytimes->store relating to a particular store.
Is there a quicker way to find out whether a given store ID exist in orderdaytimes->store pivot table.
Upvotes: 0
Views: 50
Reputation: 62338
If you don't need the actual intermediate data, you can simply query the relationships:
if ($user->orders()
->whereHas('orderdaytimes', function ($query) use ($day) {
return $query->where('date', $day);
})
->whereHas('orderdaytimes.stores', function ($query) use ($store) {
return $query->where('id', $store->id);
})
->exists()) {
// store id exists
}
You can read more about querying relationships in the documentation here.
Upvotes: 1