Question

Explanation for the use of $condition and $param in findByAttributes in Yii

In most case, this is how I use findByAttributes

Person::model()->findByAttributes(array('first_name'=>$firstName,'last_name'=>$lastName));
Was it helpful?

Solution

OTHER TIPS

When you do a find in Yii's CActiveRecord using the attributes of the model, you would most likely find by some equality.

Person::model()->findByAttributes(array(
  'first_name' => $firstName,
  'last_name' => $lastName,
));

In English, this translates to "Find me a person whose last name is $lastname and whose first name is $firstname". But this is a bad example. Consider the following.

Person::model()->findByAttributes(array(
  'age' => 18,
));

This is a better example which translates, in English, to "Fetch me all eighteen year olds" (that is, "where age = 18). This can be re-written with conditions like so

Person::model()->findByAttributes(array(
  'condition' => 'age = :age',
  'params' => array(
    ':age' => 18,
  ),
));

So far, there may seem to be little benefits. But such expressions make us able to use more boolean operators. For example...

Person::model()->findByAttributes(array(
  'condition' => 'age < :age',
  'params' => array(
    ':age' => 18,
  ),
));

...can now help us find all those below a certain age.

The query can grow as complex as you wish with $conditions and $params, but with your normal method, you may only use assignment queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top