I have two Models called Channel
and AppUser
which are related through a pivot table called app_user_channels
.
Users are able to "follow" many channels, and channels can have many users so I defined my relationship as follows:
class AppUser extends Model {
protected $fillable = ['country'];
public function channels () {
return $this->belongsToMany('App\Channel', 'app_user_channels');
}
}
class Channel extends Model {
public function appUser () {
return $this->belongsToMany('App\AppUser', 'app_user_channels');
}
}
class AppUserChannel extends Model {
public function appUser() {
return $this->belongsTo('App\AppUser');
}
public function channel() {
return $this->belongsTo('App\Channel');
}
}
I need to get the top five most recurring countries amongst the Channel's AppUsers. Now, I know that I can get the Channel's followers from the Channel Model by doing something like return $this->appUser->groupBy('country')
, but how can I get the country and count for the most common countries among the Channel's followers (AKA AppUsers)?
I'm using Laravel 5.3 and have read through the Eloquent documentation, but am still unable to figure it out. Any hints would be highly appreciated.
Try the following, the code hasn't been tested, but hopwfully, it should work. Don't forget to import DB.
return $this->appUser
->select('country', DB::raw('count(*) as total'))
->groupBy('country')
->orderBy('total', 'desc')
->get()
->take(5)
->pluck('country','total');