About Relations

Hi all,

I have 2 tables, Department and Employees with a one to many relation between them defined in the following way:-

Department model:

return array(

	'employees' => array(self::HAS_MANY, 'Employee', 'departmentId'),


Employee model:

return array(

	'department' => array(self::BELONGS_TO, 'Department', 'departmentId'),


In one of the department views, I am listing the employees for that specific department.

I was using CActiveDataProvider to get the employees of the department. I was till now using the following code:

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


	'condition'=>"departmentId=$model->id",//$model is an instance of the department




I just realised that I was not making use of the relation existing between the 2 tables and can instead use the following code:

$dataProvider = new CArrayDataProvider($results=$model->employees);

I want to be sure that I am not wrong. Can anybody confirm that this code always works in any similar situation?


Nobody to advise me? :(

Nobody to confirm if I am right? ???

did you try your second alternative <_<

Thanks Luc for your reply, yes, I tried it and it worked. I was a bit amazed and found that it seemed too good to be true. That’s why I want confirmation of it :unsure:

they are different ways to achieve the same goal. ;D

Maybe one of them could be better in terms of database access (to know that set the ‘enableProfiling’ parameter to true in the database component in config/main.php see here

Thanks for the precious advice and link. Must definitely try it to see the difference in performance. ;)