在提到@JarekTkaczyk的方法时,我试图统计一个国家的所有人。
- 一座城市
hasMany
人 - 一个国家
hasMany
个城市
在Country中使用hasManyThrough
,类似于
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
- 如何使查询删除其他列
- 我该如何将每节课的学生数相加为一个值呢
编辑:关于第二点的更多细节:
当我使用新建立的关系式peopleCount
来计算一个国家的所有人时,它是通过计算属于该国家的城市中的所有人来实现的,从而返回与每个城市对应的计数集合,例如:
>>> $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')
因此,我宁愿在查询内部完成这一切,也不愿在php端完成。
根据@Jarek Tkaczyk的回复,我所要做的就是在分组子句中对country_id