I have this code in my Work class (extends CActiveRecord), with a relation to the Media class:
public function relations()
{
return array(
'media' => array(
self::MANY_MANY,
'Media',
'ass_media(work_id,media_id)',
'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?
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(
'order'=>$model->getRelatedOrder($sortMedia),
// getRelatedOrder() is a method i put in a behavoir
)
);
$this->render('view',array(
'model'=>$model
));
}