[SOLVED] count number of relations in CGridView

Hi there,

I’m am just wondering if I can use CGridView to display the number of relations a user has, eg display the number of posts each user has made? I’ve related the ‘users’ and ‘posts’ tables fine and I can pull details of any related post from the ‘posts’ table without a problem for any given user, but I don’t know how to sum them using CGridView, so it displays something like:


Username     Posts      


Foo           11

Bar           45

I don’t want to make the total number of posts a link or anything, I just want to display it as a number in the CGridView table for reference.

Thanks,

Stu

bump

Anyone have any suggestions at all?

You can use a STAT query




'posts' => array(self::STAT, ...),



/Tommy

Hi tri,

Thanks for the tip off, that looks like the way to go, however I can’t get it to work, I think I’m missing something really obvious!

I have in my Users model relations:


'postcount'=>array(self::STAT, 'Posts', 'user_id'),

and in my CGridView call:


$this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'user-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'username',

		array(

			'name'=>'postcount',

			'value'=>Posts::model()->count(array(

				'condition'=>'user_id = :userID',

				'params'=>array(

					':userID'=>$model->id,

				),

			)

		),

		array(

			'class'=>'CButtonColumn',

		),

	),

));

This puts the postcount column in, but it’s always 0. I think it’s the ‘params’ line that’s not pulling the $model->id for each line, but is sending through to CGridView with value 0, so it’s looking for all posts with user_id as 0, hence no results?

[font="Times"][size="2"][font="arial, verdana, tahoma, sans-serif"][size="2"]

You can access postcount as an attribute of User model:[/size][/font][/size][/font]

[font="Times"][font="arial, verdana, tahoma, sans-serif"][/font][/font][size="3"][size=2]

[/size][/size]

[font="Times"][size="2"][font="arial, verdana, tahoma, sans-serif"] [/font]




$this->widget('zii.widgets.grid.CGridView', array(

	'id' => 'user-grid',

	'dataProvider' => $model->with('postcount')->search(),

	'filter' => $model,

	'columns' => array(

		'username',

		'postcount',

	),

	//...

));



[/size][/font]

That’s brilliant, I knew I had something in the wrong place, thanks a lot for that! Makes much more sense doing it your way heh