Sort on added attribute in model

I have added a extra attribute (or property) in the model.




        protected $rating;


        public function getRating()

        {

            $likes = $this->getAttribute('likes');

            $dislikes = $this->getAttribute('dislikes');

            if ($likes != 0 && $dislikes != 0)

                return $likes / ($likes + $dislikes) * 10;

        }



…and my controller:




	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Game');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}



View:




<?php $this->widget('zii.widgets.CListView', array(

	'dataProvider'=>$dataProvider,

	'itemView'=>'_view',

        'enablePagination'=>true,

        'enableSorting'=>true,

        'sortableAttributes'=>array(

            'name',

            'releaseyear',

            'developer',

            'rating',

        ),

        'template'=>'{sorter}{items}{summary}{pager}'

)); ?>



What I want to accomplish is to sort on Rating, but as you can see on the picture provided, the "link" is not clickable. Any suggestions?

Withou looking closer, first thing i see: $rating must be public.

I don’t think you can sort on calculated columns, and even if you were to do it this would happen in-memory, which means if you have a large dataset you’d have to retrieve the entire dataset into memory to be able to do the sort, which is terribly inefficient and would result in very poor performance. You’re much better off adding another column called rating to your DB and putting the total in there and then indexing that column. That way you’ll be able to leverage the DB to do the sorting using indexes and this would achieve the best result.