jeudi 15 mars 2018

Laravel: How to do multiple aggregations in a "has through" relationship in a single query

I have the following tables:

Venues

  • id

Offers

  • id
  • venue_id

Orders

  • id
  • offer_id
  • quantity

Venues can have many offers, and offers can have many orders. This is all modelled in the appropriate eloquent models like so:

class Venue extends Model
{
    public function offers()
    {
        return $this->hasMany(Offer::class);
    }
}

class Offer extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

I want to run a single query which allows me to see every venue and the number of orders it has. e.g.

venue_id | number_of_orders
---------------------------
5        | 20
15       | 0
8        | 123

I was easily able to do this using raw SQL like so:

select venues.id, sum(offersGrouped.number_of_orders) as total_number_of_orders
from venues
left outer join (
   select offers.id, offers.venue_id, sum(orders.quantity) as number_of_orders
   from offers
   left outer join orders on offers.id = orders.offer_id
   group by offers.id
) offersGrouped on venues.id = offersGrouped.venue_id
group by venues.id;

However, how can I do the same thing using Eloquent?

I am using Laravel 5.1, but I don't mind if answers uses features from newer versions of Laravel if required.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire