Turning to the @JarekTkaczyk method, I am trying to count all the people in the country.
- City
hasManyPeople - A Country
hasManyCities
using hasManyThroughin the Country, for example:
public function peopleCount(){
return $this->hasManyThrough('App\Person', 'App\City')
->selectRaw('city_id, count(*) as count')
->groupBy('city_id');
}
I can access the number of people in each city. But it returns more than just two fields city_idand count! The account is correct, but the rest of the data is not what I would like there. Here is an example: http://i.imgur.com/o1fyvEy.png
- How to force a query to delete other columns?
- How can I go further than counting students in each class, summing up all the scores by one value?
Edit: more about the second point:
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-side.