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.