Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Count number of rows in a relationship

I have the following relationship:

  • A venue has many offers
  • A offer has many orders

I have the following Eloquent model to represent this:

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:

$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.

like image 578
Yahya Uddin Avatar asked Dec 24 '22 13:12

Yahya Uddin


1 Answers

You can use Eloquent. As of Laravel 5.3 there is withCount().

In your case you will have

$venues = Venue::where('location_id', 5)->with('orders')->withCount('orders')->get();

Then access it this way

foreach ($venues as $venue) {
    echo $venue->orders_count;
}

Can find reference here: https://laravel.com/docs/5.3/eloquent-relationships#querying-relations

like image 118
Svetlin Yotov Avatar answered Jan 05 '23 19:01

Svetlin Yotov