9 months ago

ActiveCount of sub relationship of sub relationship..

Posted 9 months ago by binggle

I am building system with 3 models

  1. Nation has many Minister ;
  2. Each Minister has many Officer

I have 3 models ( Nation, Minister , Officer )

Model : Nation

function ministers(){
    return $this->hasMany( Minister::class );

Model : Minister

function officers(){
    return $this->hasMany( Officer::class );

function officersActiveCount(){
    return $this->hasMany( Officer::class)->where('state', 'active' )->count();

The following is workng ok . It gets all officers with corresponding ministers .

$nation = Nation::where('id', $nation_id)->with('ministers.officers')->get();

But I want to get 'ministers' and 'officersActiveCount' NOT 'officers'

How can I get the officersActiveCount with each nations ?

Please sign in or create an account to participate in this conversation.