Click here for EduSec Demo EduSec Screenshots

Search By reference or Search by Foreign key Name

On 2013-06-10 - By Ravi Thanki

Below post is about search by foreign key in admin gridview.

Generally we insert id of master table into child table at time of display id will display in admin gridview but we want to display actuall value of id's and implement searching on it.

Lets. understand by following example.

Example:

table: user (user_id,user_name)
table: employee (emp_id,emp_name,user_id)

In employee table user_id is foreign key of user table.

When I create a model on employee I was able to search(yii built in) on user_id.

This is the view file

$this->widget(‘zii.widgets.grid.CGridView’, array(
‘id’=>’manager-grid’,
‘dataProvider’=>$model->search(),
‘filter’=>$model,
‘columns’=>array(
‘emp_id’,
‘emp_name’
‘user_id’,

if i want search for User Name in this model but not by user_id.

Step: 1 Define public user_name field of user table in employee model.

public $user_name;

step: 2 Define user_name in search criteria in rules function in employee model.

step: 3 Define relation in relation function of employee model.

e.g. ‘Rel_user_id’ => array(self::BELONGS_TO, ‘(name of model here) User’, ‘(employee table’s user id field here) user_id’),

step: 4 In search function of employee model define like this

$criteria->with = array(‘Rel_user_id’);// name of relation
$criteria->compare(‘Rel_user_id.user_name’,$this->user_name,true); // comparison

step: 5 In admin file define like this

array(
‘name’=>’user_name’,
‘value’=> ‘$data->Rel_user_id->user_name ‘,
),