Question

say with a structure like this., columns are :

first_name | second_name | middle_name | last_name

Now, suppose i have a form that requires to enter a "name"..but not specifying what type of name it is.

And on the controller, i have to check whether that "name" is in the database.

I do it like this:

public function actionCheckName($name){

$name = PersonName::model()->findByAttributes(array('first_name'=> $name));
//then check if the name exists in the first_name column

if(!empty($name)){
$name = PersonName::model()->findByAttributes(array('second_name'=> $name));
}
//if it's not in the first_name column...check in the second_name column

..
..and so on, i hope you get the idea

}

i basically don't know whether what type of name did the user enter... but i have to check in the database if the entry exists..whether in one of these name types.

the code above works.but looks..a little...not-so-good.. Is there a better way to do this? Many Thanks!

Was it helpful?

Solution

        $criteria=new CDbCriteria;
        $criteria->compare('first_name', $name, false, 'OR'); // The 3th param determine if the string comparation use "LIKE" or "="
        $criteria->compare('second_name', $name, false, 'OR');
        $criteria->compare('middle_name', $name, false, 'OR');
        $criteria->compare('last_name', $name, false, 'OR');

        $nameList = PersonName::model()->findAll($criteria); // Return all PersonName with $name in any field.

        $name = PersonName::model()->find($criteria); // Return the first PersonName with $name in any field.

OTHER TIPS

I think you could use criteria like this

$q = new CDbCriteria( array(
'condition' => "first_name LIKE ':first_name%' || last_name LIKE ':lname%'... and so on",     
'params'    => array(':first_name' => $fname,':lname'=>$lname .. and so on)

) );

$name = PersonName::model()->find($q);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top