Reputation: 662
I need to find all schools with contains a certain emailaddress in a string
At this moment, I'm sending a query to my database to obtain a list of Schools like this
$aSchools = School::model()->findAllByAttributes(array(
'finished' => School::SCHOOL_CREATED,
));
After that, I itterate over all the schools to check if they containt the mailAddress like this:
$aFoundSChools = array();
foreach($aSchools as $oSchool)
{
if (strpos($oSchool->mailAddress, Yii::app()->user->mailAddress))
{
$aFoundSChools [] = $oSchool;
}
}
But I'm guessing this could be cleaner, right? Can i do that in a single function, like a 'LIKE' query in sql?
Upvotes: 0
Views: 806
Reputation: 36784
MongoDB supports "like" queries in the form of regular expressions. Be warned though that this can not use an index. From plain PHP, you'd construct it like this:
$query = array(
'finished' => School::SCHOOL_CREATED,
'mailAddress' => new MongoRegexp( '/' . addslashes( Yii::app()->user->mailAddress ) . '/' ),
);
You'll have to use the addslashes if you think your mail address might contain a /
.
I don't quite know Yii, but I expect you can use $query
like this, just replacing your already existing test for just 'finished':
$aSchools = School::model()->findAllByAttributes( $query );
Upvotes: 1