use find() with GET[id] and match it with a column

I have a CGridview that lists employees, when you click on a employee you will be redirected to the view of that id. In this view I show information about the employee. Below the information I want to display a CGridview with information about all the projects this particular employee has worked with.

The employee-table has not a column for "projects", but the project-table has an employee_id.

I guess the easiest way would be to use the GET[id] from the url and just call the project-model and match it with the employee_id.

Im new to yii so im wondering which of the find() methods I should use. I want to use GET[] and match it with a column in the projectmodel. Is this possible? Maybe there is a better way to handle this?


just define a relation between your two models in Employee model:

'projects' => array(self::HAS_MANY, 'Project', 'employee_id'),

You can fetch than the data with:

$model = Employee::model()->with('projects')->findByPk($your_employee_id);

$id = CPropertyValue::ensureInteger($_GET['id']);

$employee = Employee::model()->findByPk($id);


$projects = Project::model()->findAllByAttributes(array('employee_id'=>$id));

or just

$projects = $employee->projects

if you use relations

hope this helps.

I highly recommend using model relations from beginning to get your data with only one query.

I tried with yiwis method.

I can’t get it to display the rows in the CGridview.

I guess I need to do something instead of $model=new Employee(‘search’); ?

This is my controller:

public function actionView($id)


		$model = Employee::model()->with('projects')->findByPk($id);






and this is in the view:

<?php $this->widget('zii.widgets.grid.CGridView', array(










)); ?>


you should definitely take a look at the yii guide and wiki.

This should do the trick:

$dataProvider = new CActiveDataProvider(Projects::model(), array(

    'criteria'=>new CDbCriteria(array(

            'condition' => 'employee_id=?',

            'params' => array($id),




$this->widget('zii.widgets.grid.CGridView', array(











Will do! Think it’s a bit messy tho :confused:

It works now, thanks!

One question tho, in this code:

'condition' => 'employee_id=$id',

I tried to insert an $id variable but I only get errors, I guess that the variable is handled as a string, how can i escape this?





This ensures that no malicious content can be passed, because yii automatically encodes the variables.


Is there an easy way to implement the advance-search in this CGridview?

Just take a look at this tutorial:

As you can see, you must add the $filter property to create a search behaviour.