37

Could you provide an example usage. Description will be highly appreciated. I can not find a good example for it.

ActiveQuery in Gii

akmnahid
  • 736
  • 2
  • 6
  • 18

1 Answers1

94

The Active Query represents a DB query associated with an Active Record class. It is usually used to override the default find() method of a specific model where it will be used to generate the query before sending to DB :

class OrderQuery extends ActiveQuery
{
     public function payed()
     {
        return $this->andWhere(['status' => 1]);
     }

     public function big($threshold = 100)
     {
        return $this->andWhere(['>', 'subtotal', $threshold]);
     }

}

If you worked before with Yii 1 then this is what replaces Yii 1.x Named Scopes in Yii2. All you have to do is to override the find() method in your model class to use the ActiveQuery class above :

// This will be auto generated by gii if 'Generate ActiveQuery' is selected
public static function find()
{
    return new \app\models\OrderQuery(get_called_class());
}

Then you can use it this way :

$payed_orders      =   Order::find()->payed()->all();

$very_big_orders   =   Order::find()->big(999)->all();

$big_payed_orders  =   Order::find()->big()->payed()->all();

A different use case of the same ActiveQuery class defined above is by using it when defining relational data in a related model class like:

class Customer extends \yii\db\ActiveRecord
{
    ...

    public function getPayedOrders()
    {
        return $this->hasMany(Order::className(),['customer_id' => 'id'])->payed();
    }
}

Then you can eager load customers with their respective payed orders by doing :

$customers = Customer::find()->with('payedOrders')->all(); 
Salem Ouerdani
  • 6,956
  • 2
  • 37
  • 47
  • 5
    gem of an answer. So well described. Loved it thank you :) – Gogol Jan 25 '16 at 18:44
  • 3
    pleasure is mine @noc2spamツ I'm glad it helped. Thanks – Salem Ouerdani Jan 25 '16 at 19:18
  • Is it possible to modify the Select statement as well? – geilt Jun 16 '17 at 01:22
  • Yes @geilt [select](http://www.yiiframework.com/doc-2.0/yii-db-query.html#select()-detail) and [addSelect](http://www.yiiframework.com/doc-2.0/yii-db-query.html#addSelect()-detail) are [ActiveQuery](http://www.yiiframework.com/doc-2.0/yii-db-activequery.html) methods we can use. Here is an example: https://stackoverflow.com/questions/43840406/yii2-how-to-set-scenario-in-dataprovider/43848957#43848957 – Salem Ouerdani Jun 16 '17 at 08:02