从两个模型中显示Yii Gridview中的计数数据

从两个模型中显示Yii Gridview中的计数数据

问题描述:

I have 2 tables, servers and ip, in ip table I am saving server_id. Now I want to show on server listing page how many total ips related to one server?

MY Server model code:

   class Server extends CActiveRecord {

        public function relations(){
     return array('ipmodel'=>array(self::BELONGS_TO, 'IpManager', 'server_id'),
        );
       }
     }

My CGridView Code:

     array( 
        'header' => 'IP Count',
        'value' => 'count($data->ipmodel)',
     ),

It is showing only 1 but there are so many ips against to one server! How I can do this?

Change relation!

      'ipmodel'=>array(self::HAS_MANY, 'IpManager', 'server_id')

The best way is to use inbuilt STAT relation of Yii framework:

Relation:

'ipmodelcount'=>array(self::STAT, 'IpManager', 'server_id')

In grid view use it directly:

array( 
  'header' => 'IP Count',
  'value' => '$data->ipmodelcount',
),

Explaination:

why use STAT relation for count?

HAS_MANY will load all related model's data while STAT relation run count query on server for related data. So using STAT will take less execution time to provide desire result.