简体   繁体   中英

Aggregate function on Eloquent relation

I have done plenty of searching on this topic but cannot find a clear and concise answer as to whether it is possible in Eloquent.

Say for example we have two models Manufacturer & Car with a one to many relationship.

Manufacturer.php

public function cars()
{
     return $this->hasMany('App\Car');
}

Car.php

public function manufacturer()
{
     return $this->belongsTo('App\Manufacturer');
}

With plain old SQL I can efficiently do the following:

SELECT
m.id,
m.slug,
m.title,
m.content,
ROUND(AVG(NULLIF(c.status ,0))) AS 'score'
FROM 
manufacturers m
INNER JOIN cars c ON c.manufacturer_id = m.id 
GROUP BY m.id

I wish to do the same in eloquent. I have tried various things but I cannot seem to see how to include the AVG function on the cars status column.

I can get all the manufacturers and their related cars with the following:

$manufacturers = App\Manufacturer::with('cars')->get();

But if I add the AVG to the query event with DB::raw it complains that the column does not exist. Is it possible to retrieve the AVG column as part of the result in this manner in Eloquent or must it be done separately after the retrieval has been completed.

I could of course rewrite the query in a DB query builder syntax but for this particular use case it's a little counter intuitive.

Also I do realise that Eloquent is just a wrapper for the DB fluent syntax but I was wondering if it is possible to do this in eloquent type syntax.

Here is the eloquent way:

App\Manufacturer::join('cars as c', 'manufacturers.id', '=', 'c.manufacturer_id')
        ->select('manufacturers.id', 'manufacturers.slug', 'manufacturers.title', 'm.content', DB::raw("ROUND(AVG(NULLIF(c.status ,0))) AS 'score'"))
        ->with('cars')
        ->groupBy('manufacturers.id')
        ->get();

Unfortunately there is no way to define alias in query of the eloqent model for manufacturers table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM