Search By reference or Search by Foreign key Name
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.
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
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.
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
‘value’=> ‘$data->Rel_user_id->user_name ‘,