Yii Framework Forum: search on HAS_MANY - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

search on HAS_MANY Rate Topic: -----

#1 User is offline   wuadziu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 26
  • Joined: 28-November 11
  • Location:Dresden/Saxony

Posted 18 July 2012 - 07:08 AM

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 ?
0

#2 User is offline   vibhaJadwani 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 13-June 12
  • Location:India

Posted 18 July 2012 - 08:42 AM

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
}
exit;

2

#3 User is offline   wuadziu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 26
  • Joined: 28-November 11
  • Location:Dresden/Saxony

Posted 19 July 2012 - 05:48 AM

View PostvibhaJadwani, on 18 July 2012 - 08:42 AM, said:

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
}
exit;


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: http://www.yiiframew...teria-together/
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users