计数然后在laravel 5中求和二度关系 [英] Count then Sum a second degree relation in laravel 5

查看:1200
本文介绍了计数然后在laravel 5中求和二度关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在引用@ JarekTkaczyk的方法,我想计算一个国家的所有人。

While referring to @JarekTkaczyk's method, I am trying to count all people in a country.


  1. 城市 hasMany 人们

  2. 国家 hasMany 城市

  1. A City hasMany People
  2. A Country hasMany Cities

在国家/地区使用 hasManyThrough ,如下所示:

using hasManyThrough in Country, like so :

public function peopleCount(){
    return $this->hasManyThrough('App\Person', 'App\City')
        ->selectRaw('city_id, count(*) as count')
        ->groupBy('city_id');
}

我可以访问每个城市的人数。但是它不仅返回两个字段 city_id count !计数是正确的,但其余的数据不是我想要的。以下是一个示例: http://i.imgur.com/o1fyvEy.png

I can access the count of People in each city. Yet it returns more than just the two fields city_id and count ! the count is correct, but the rest of the data is not something I'd want there. Here is an example : http://i.imgur.com/o1fyvEy.png


  1. 如何让查询删除其他列?

  2. 如何进一步比点数学生每个课程通过将所有计数合并为一个值?

编辑:更多关于第二点的细节:

Edit : more details on point two :

当我使用新的关系 peopleCount 来统计一个国家的所有人,这样做是通过统计所有属于国家,因此返回与每个城市相对应的计数的集合,示例如下:

When I use the new made relation peopleCount to count all people in a country, it does so by counting all people in cities that belong to the country, thus returning a collection of counts that corresponds to each city, example in the following :

>>> $country = App\Country::with('peopleCount')->find(1)
=> <App\Country> {
       id: "1",
       peopleCount: <Illuminate\Database\Eloquent\Collection> [
           <App\Person> {
               city_id: "1",
               count: "3", //<-------
               id: "1",
               country_id: "1"
           },
           <App\Person> {
               city_id: "2",
               count: "5", //<-------
               id: "4",
               country_id: "1"
           },
           <App\Person> {
               city_id: "3",
               count: "8", //<-------
               id: "9",
               country_id: "1"
           }
       ]
   }

计数我做它PHP边而不是数据库这样: $ country-> peopleCount-> sum('count')

To get the sum of counts I do it PHP side rather than database side like so : $country->peopleCount->sum('count')

所以我宁愿在查询中做所有这一切,而不是做php-side。

So I would rather do it all inside the query than doing it php-side.

推荐答案

@Jarek Tkaczyk的答复我所要做的只是在groupby子句

as per @Jarek Tkaczyk's response all i had to do was to country_id in the groupby clause

这篇关于计数然后在laravel 5中求和二度关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆