dongwen7371 2016-05-12 10:11
浏览 158
已采纳

Eloquent关系的聚合函数

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.

  • 写回答

1条回答 默认 最新

  • dongmao3131 2016-05-12 10:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改