How To Load Relationshep Values In Listdata()


I need to know how to call relationship in listData() ,

For Example in normal way we can call it like :

$model->section->section_name ;

in my code i just print value as number but I need to print string value from courses table .

   public function coursesList($section_id) {







    	return CHtml::listData($data,'course_id','course_id');

 //// can i call it like : ///listData($data,'course_id->course->course_name','course_id');


Can I call it like?


How To fix that ?

thanks in advance

Yes, you can do it as


where course is a relation.

Further Value funcion

Thanks PeRoChAk but Not Work , This is my relations , it’s just print course_id when use your code

public function relations()


		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'section' => array(self::BELONGS_TO, 'Csection', 'section_id'),

			'course' => array(self::BELONGS_TO, 'Courses', 'course_id'),



Can you show your code here

Dear Friend

I think what PeRoChAk suggested should work.

Else Kindly check the following in your case please.

$sections=Msection::model()->findAll('section_id=:section_id', array(':section_id'=>(int)$section_id));

CHtml::listData($sections,function($section){ //You can pass the anonymous functions from second parameter on wards.

       return CHtml::encode($section->course->course_name);



OK , Thanks

In my use case, the current model has a HAS_MANY relationship with the model whose attribute I need to access, so I cannot get a single value as an attribute of this relation. But I have this value defined in a variable already, as the listData function is actually within a foreach loop that iterates this relation.

I came up with this workaround that let me access that related attribute:


[*]Add a BELONGS_TO relation to the pivot model.

[*]Use the pivot model instead of the real model.

[*]This way the pivot model is passed over to the anonymous function, so you can access the relation’s attribute directly.


It works but I would like to know whether there is a more straightforward solution. Is there any simpler way to access another variable from within the anonymous function?