search on HAS_MANY

hi, i have a Client model, which can have an infinite amount of phone numbers. the Phone model consists just of its ID, the client’s ID and the number itself.

so i have a HAS_MANY relation in the Client model:

public function relations()


  'phones' => array(self::HAS_MANY, 'Phone', 'client_id'),


now i want to do a search on the clients providing a phone number, so if there is a phone with the given number it will give me its client.

does anyone have any ideas how to proceed ?

Try below code:

‘98’ => is the number you are searching

‘firstName’ => is any field from Client model

$criteria = new CDbCriteria;

$criteria->with = array('phones');

$criteria->compare( 'phones.value','98', true ); // 98 is the search string

$results = Client::model()->findAll($criteria);

foreach($results as $record)


	echo '=>'.$record->firstName ;// client firstName



i forgot to mention that i want to use the CDbCriteria in a CActiveDataProvider. i haven’t tried your whole code, but the first three lines are ok, but if you want to use it in a data provider you have to add:

$criteria->together = true;

in case someone else has a similar problem, here’s a link: