Count the records of an With part of query

I just want to know how many records are in the database without retreiving them; Here is what I did;




 $model= country::find()->with(

    ['towns'=>function($query){ 

           $nombret=$query->count();

    },

        'groups'=>function($query){

             $nombreg= $query->count();

    },

        'provinces'=>function($query){

            $nombrepr= $query->count();

    },

        'people'=>function($query){

           $nombrep= $query->count();

    },'quarters'=>function($query){

           $nombreq= $query->count();

    }])->where(['idcountry'=>\yii::$app->request->get('idcountry')])->one();

When I try to echo $nombret,$nombrepr,… they are 0 even if the are records in the database but if I do


$nombret=count($model->towns)

and then echo $nombret I get the exact number but with that it is loading the all records from the database.

Is there any other good way of doing that and get how many records connect to the current model are in DB?

Thanks;

Check this section of the guide.

ActiveRecord - Selecting extra fields




$model = Country::find()

    ->select([

        '{{country}}.*', // select all country fields

        'COUNT({{town}}.id) AS townsCount' // calculate towns count

        ...

    ])

    ->joinWith('towns') // ensure table junction

    ...

    ->groupBy('{{country}}.idcountry') // group the result to ensure aggregation function works

    ->where(['idcountry'=>\yii::$app->request->get('idcountry')])->one();