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.

Entities/Attributes.


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(

		'id'=>'user-grid',

		'dataProvider'=>$model->search(),

 		'filter'=>$model,

		'columns'=>array(

				

			  array('name'=>'first_name',

				'header'=>"First Name",

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

				

			    array('name'=>'user_id',

				'header'=>User::model()->getAttributeLabel('username'),

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

				'type'=>'raw',

                 ....................


// 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 !

Hi TNC,

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:

http://www.yiiframework.com/doc/guide/1.1/en/database.arr

Or you may want to read this wiki article first.

http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview

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


 compare->with ''

part in my model search function. Got it.