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



Can name of the column be anything ?

Dear Friend

To simulate your scenario, I have following tables.



Post belongs to Author through a_id.


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";	

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




		return new CActiveDataProvider($this, array(





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





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







		'lastPost',//The virual property






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


yes you can change the name of the column