I have the following relationship:
- A venue has many offers
- A offer has many orders
I have the following Eloquent model to represent this:
JavaScript
x
class Venue {
public function orders()
{
return $this->hasManyThrough(Order::class, Offer::class);
}
}
I want to determine the total number of orders for venues with location_id = 5
using Laravel’s Eloquent model.
The only way I managed to do this is as follows:
JavaScript
$venues = Venue::where('location_id', 5)->with('orders')->get();
$numberOfOrders = 0;
foreach($venues as $venue) {
$numberOfOrders += $venue->orders->count();
}
dump($numberOfOrders); // Output a single number (e.g. 512)
However, this is obviously not very efficient as I am calculating the count using PHP instead of SQL.
How can I do this using Eloquent model alone.
Advertisement
Answer
You can use Eloquent. As of Laravel 5.3 there is withCount()
.
In your case you will have
JavaScript
$venues = Venue::where('location_id', 5)->with('orders')->withCount('orders')->get();
Then access it this way
JavaScript
foreach ($venues as $venue) {
echo $venue->orders_count;
}
Can find reference here: https://laravel.com/docs/5.3/eloquent-relationships#querying-relations