Dynamically sort related AR models

I have this code in my Work class (extends CActiveRecord), with a relation to the Media class:

public function relations()


	return array(

		'media' => array(




		    'order'=>$this->getRelatedSortOrderDetails('media') // THIS DOES NOT WORK




Of course, it does not work since ‘order’ should be static (somehow defined in the model class, before being instantiated i guess). Also using behaviors it does not work.

What is the right and cleanest way to order AR related models dynamically? Could you please post an example?

Many thanks if you could help :)

haven’t you read the guide ? :angry:


do not be too bad with me, i’m still learning Yii. ;)

yes, of course i’ve read that already. but i still cannot make it work with CActiveDataProvider:

$dataProvider = new CActiveDataProvider('Work', array(

                        'criteria' => array(

                            'condition' =>  'id=' . $model->id,




                                        'select'=>'id, title, url, mime',

					'order'=>'ass_work_media.sort_order ASC' // DOES NOT WORK





i know that must be something very simple, but i do not know what is wrong… no errors though, in this case: it simply does not apply any order.

question: maybe the problem is that the sort order is in the associative table and not in the related model table?

the associative table has 3 columns: work_id, media_id, sort_order because i need to have manual sorting too.

yiqing95 put me in the right path and i could finally find a possible solution. In the controller action (for example actionView) you simply do:

public function actionView($id)


		$model = $this->loadModel($id);



		 * Get sort type for related models (from sort_media column).


		$sortMedia = $model->sort_media;



		 * Related data: media.


		$model->media = $model->media(array(


			// getRelatedOrder() is a method i put in a behavoir








Then you can access related models as usual:


Thank you very much for your help.