Nested Relational criteria in search()

I’ve just spent a few hours trying to figure this out, turns out you can nest relational criteria in the search() function in a model.

Like this:

$criteria->with = array('event' => array('with' => 'student_user'));

$criteria->compare("student_user.username", $this->student_username, true);

Both ‘event’ and ‘student_user’ are BELONGS_TO relations. ‘student_username’ is a public variable defined at the beginning of my model (and set as safe in my rules). I’ve been trying use the following in my CGridView widget columns:


    'name' => 'student_username',

    'header' => 'Student',

    'type' => 'raw',

    'value' => '$data->event->student_user->username'


The nested criteria helped me get the search function working, hope this helps someone :)


Thank you SO much for this post! You just saved me hours of frustration. It is amazing how simple that nested "with" statement works. One thing that had me confused is that I was trying to do the equivalent of


and it kept giving me the error “Unknown column ‘event.student_user.username’ in where clause”. I still think it is a bit strange that you just use student_user.username. I imagine this is standard convention for JOIN queries. I’m just not that familiar with them.

Once again, I amazed at how powerful and awesome Yii is.

I’m glad it helped :)

Hi jcsmesquita,

in which model have you done this?

Hi cappadochian,

I did it in the parent model "Events".

Yes You Can, and it is even easier if you use my RelatedSearchBehavior: .