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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?