Cgridview And Has_Many Relation

I have 2 models, author and post. Author has many posts, post belongs to only one author.

Also i have a cgridview in which I list all authors. Now I need to list all authors with theirs last post’s name.

So post model’s name attribute is column of cgridview. How do I do this?

Hi Jijgee if you have relationship defined in the both models, then you can do some as following in your gridview


'name'=>'postName',

'value'=>'$data->posts[0]->name',

Can name of the column be anything ?

Dear Friend

To simulate your scenario, I have following tables.

author:id,name

post:id,title,created(DATETIME),a_id.

Post belongs to Author through a_id.

Author.php




class Author extends CActiveRecord

{  


//Declare a virtual property latPost 

	public $lastPost;


//Make it safe on search

        public function rules()

	{

		return array(

			array('name', 'required'),

			array('name', 'length', 'max'=>64),

			array('id, name,lastPost', 'safe', 'on'=>'search'),

		);

	}


//Though I have defined relation below I have not used it for this pupose.

        public function relations()

	{

		return array(

			'posts' => array(self::HAS_MANY, 'Post', 'a_id'),

		);

	}




//Making a subquery to fetch the last created record.

        public function search()

	{

		$criteria=new CDbCriteria;

		$criteria->select="t.*,title AS lastPost,created";

		$criteria->join="LEFT OUTER JOIN post on a_id=t.id";	

		$criteria->condition="created =(SELECT MAX( created )FROM post WHERE a_id =t.id )";


		$criteria->compare('id',$this->id);

		$criteria->compare('name',$this->name,true);

		$criteria->compare('title',$this->lastPost,true);


		return new CActiveDataProvider($this, array(

		    'criteria'=>$criteria,

		    'sort'=>array("attributes"=>array(

	                'id',

                        'name',

                        'lastPost'=>array('asc'=>"title ASC",'desc'=>'title DESC'),

                           )),

		));

	}



admin.php




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

	'id'=>'author-grid',

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

	'filter'=>$model,

	'columns'=>array(

		'id',

		'name',

		'lastPost',//The virual property

		array(

			'class'=>'CButtonColumn',

		),

	),

)); 



Now we can display,sort and search on lastPosts made by authors.

Regards.

yes you can change the name of the column