Search In Related Field


In my "usuario" table I have a field called "principal_objetivo" that belongs to id from "principal_objetivo" table.

I changed my grid view to show “nombre_objetivo” (objetive name) instead of the id but I can’t make the search work. If I search by the id works but it doesn’t when I input the “nombre_objetivo”. This is what I’ve done.






relation made by gii in Usuario model:

'principalObjetivo' => array(self::BELONGS_TO, 'PrincipalObjetivo', 'principal_objetivo'),

relation made by gii in PrincipalObjetivo model

'usuarios' => array(self::HAS_MANY, 'Usuario', 'principal_objetivo'),

Usuario model, search function:

$criteria->compare('principal_objetivo',$this->principal_objetivo); //made by gii and allows me to search by id

$criteria->with =array('principalObjetivo'); //I've added this line and the following one to search by the name

$criteria->addSearchCondition('principalObjetivo.nombre_objetivo', $this->principal_objetivo);

Usuario model, rules. I’ve tried with and without ‘principalObjetivo’ in there.

array('principal_objetivo, principalObjetivo', 'safe', 'on'=>'search'),

I can’t figure what I’m doing wrong as I followed a guide step by step and I checked it a lot of times.

Any help? Thanks.

It is almost same as your example.

you try to use "$this->principal_objetivo" in both search conditions - comparing to both id and nombre… strange that it works in any case…

you need separate attribute for nombre search, or you need to decide wheter you want to use principal_objetivo to search by foreign key (principal_objetivo) or nombre_objectivo column…

I created this public property and I added it to safe on search.

public $nombreObjetivo;

I also added it here:

$criteria->addSearchCondition('principalObjetivo.nombre_objetivo', $this->nombreObjetivo, true);

It works now. I don’t understand how but it does.

Now I realize that I posted the same issue some days ago but I couldn’t find my own thread, sorry.

I’ll read the code again to understand everything.

Thanks :)