Skip to content

Commit f1f6261

Browse files
lennartvddklimov-paul
authored andcommitted
Support compare in MongoDB (#24)
Support compare in MongoDB
1 parent c61711b commit f1f6261

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Query.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,4 +463,40 @@ private function composeSort()
463463
}
464464
return $sort;
465465
}
466+
467+
/**
468+
* Helper method for easy querying on values containing some common operators.
469+
*
470+
* The comparison operator is intelligently determined based on the first few characters in the given value and
471+
* internally translated to a MongoDB operator.
472+
* In particular, it recognizes the following operators if they appear as the leading characters in the given value:
473+
* <: the column must be less than the given value ($lt).
474+
* >: the column must be greater than the given value ($gt).
475+
* <=: the column must be less than or equal to the given value ($lte).
476+
* >=: the column must be greater than or equal to the given value ($gte).
477+
* <>: the column must not be the same as the given value ($ne). Note that when $partialMatch is true, this would mean the value must not be a substring of the column.
478+
* =: the column must be equal to the given value ($eq).
479+
* none of the above: use the $defaultOperator
480+
*
481+
* Note that when the value is empty, no comparison expression will be added to the search condition.
482+
*
483+
* @param string $name column name
484+
* @param scalar $value column value
485+
* @param string $defaultOperator Defaults to =, performing an exact match.
486+
* For example: use 'LIKE' or 'REGEX' for partial cq regex matching
487+
* @see yii\mongodb\Collection::buildCondition()
488+
* @return static The Query object itself
489+
*/
490+
public function andFilterCompare($name, $value, $defaultOperator = '=')
491+
{
492+
$matches=[];
493+
if (preg_match("/^(<>|>=|>|<=|<|=)/", $value, $matches)) {
494+
$op = $matches[1];
495+
$value = substr($value, strlen($op));
496+
} else {
497+
$op = $defaultOperator;
498+
}
499+
500+
return $this->andFilterWhere([$op, $name, $value]);
501+
}
466502
}

0 commit comments

Comments
 (0)