CDbCriteria::compare() equivalent in Yii2

In Yii 1.1 we used the compare() function in the search functions when comparing with a filter model.
In Yii 2 we are using ActiveQuery, but it does not have an equivalent function.

I want to apply to the SQL query a condition if any attribute in the model/filter is set. Example:

public function search() {
  $query = Car::find();
  if (!empty($this->brand)) $query->andWhere(['brand'=>$this->brand]);
  // this was better:
  // $criteria->compare('brand', $this->brand);

I hope there is something I am missing :slight_smile:

1 Like


Check the filter versions of xxxWhere() methods.

$query = Car::find();
//  if (!empty($this->brand)) $query->andWhere(['brand'=>$this->brand]);
$query->andFilterWhere(['brand' => $this->brand]);

There is a “compare” method in ActiveQuery:
andFilterCompare() public method (available since version 2.0.8)