Yii2 : ActiveQuery Example 以及在 Gii 中单独生成 ActiveQuery class 的原因是什么?

Yii2 : ActiveQuery Example and what is the reason to generate ActiveQuery class separately in Gii?

您能否提供一个示例用法。描述将不胜感激。我找不到很好的例子。

Active Query represents a DB query associated with an Active Record class。它通常用于覆盖特定模型的默认 find() 方法,用于在发送到数据库之前生成查询:

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

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

}

如果您之前使用过 Yii 1,那么这就是 Yii2 中 Yii 1.x Named Scopes 的替代品。您所要做的就是覆盖 模型 class 中的 find() 方法以使用上面的 ActiveQuery class :

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

那么你可以这样使用它:

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

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

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

上面定义的相同 ActiveQuery class 的不同用例是在定义 关系数据 时使用它相关 型号 class 喜欢:

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

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

然后您可以通过以下方式预先加载 客户 及其各自的 已付款订单 :

$customers = Customer::find()->with('payedOrders')->all();