Searching With Multiple Models.

Hello there, i have been through different pages and different topics to meet my specification, and finally i post here.

What i am trying to do is,

I have a UserProfile and User model.


UserProfile: id,user_id,first_name, last_name,…

User: username,id

I want to show all entities form UserProfile and User in cgridview and able to search them separately.

so i created a controller action like this.

public function actionControllerAction(){

$model = new UserProfile('search');

		$model -> unsetAttributes();

		// clear any default values

		if (isset($_GET['UserProfile']))

			$model -> attributes = $_GET['UserProfile'];


		$this -> render('MyView', array('model' => $model ));


// CGridView

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







				'header'=>"First Name",

				'htmlOptions'=>array('style'=>'text-align: center'),),




				'value' =>'$data->getRelated(\'user\')->username',



// my Model search function:

$criteria -> compare('first_name', $this -> first_name, true);

$criteria -> compare('user_id', $this->user_id, true);

return new CActiveDataProvider($this, array('criteria' => $criteria, ));

But i am not able to search by username, how can i acheive this?? Help needed !


So your User and UserProfile is in a typical relation of "HAS_ONE" and "BELONGS_TO".

User HAS_ONE UserProfile

UserProfile BELONGS_TO User

Do you have those relations already established in your model codes? I guess you have.

Then, UserProfile.php could be like this:


public $username;


public function search()



    $criteria->with = array('user');


    $criteria->compare('first_name', $this->first_name, true);

    $criteria->compare('user_id', $this->user_id, true);


    $criteria->compare('user.username', $this->username;


    return new CActiveDataProvider($this, array('criteria' => $criteria, ));


See the details in the guide:

Or you may want to read this wiki article first.

Thanks for the reply, and the answer ! I should have

 compare->with ''

part in my model search function. Got it.