yiidate-sorting

CListView sorting on data from another table


I have a table that stores information about a role. In that table I have two fields that store the ids from other tables.

Table one: id, rname, pname, idtwo, idthree

Table two: id, twoname

Table three: id, threename

My ClistView displays rname, pname, twoname, threename

With this forums help I was able to use a CListView and display the names from tables two and three.

What I would now like to do is be able to do is create a view where the information is sorted on twoname and aonther view where the data is sorted on threename.

My actionIndex is:

public function actionIndex() {
$dataProvider = new CActiveDataProvider('Staffroleprofile');
$this->render('index', array(
'dataProvider' => $dataProvider,
));
}

and my _view.php is:

<h1>List of SRP's</h1>
<?php 
$dataProvider->sort->defaultOrder='rname ASC'; 
?>

<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>    

so the above gives me the data sorted by rname from table one. How would I specify that I want the data to be sorted by the data in table two or three?

Kind regards,

e25taki


Solution

  • If model2 and model3 are the relations for table 2 and 3 respectively in Staffroleprofile, add this to your code

    $dataProvider = new CActiveDataProvider('Staffroleprofile');
    $criteria=new CDbCriteria;
    $criteria->together=true;
    $criteria->with=array('model2','model3');
    $dataProvider->criteria=$criteria;
    $dataProvider->sort->defaultOrder='model2.twoname ASC';
    

    CDbCriteria::together specifies whether the query should be run using a join. If set to false additional queries are run for each record if a relation is required. For more detail go to the API pages for CDbCriteria and CActiveDataProvider