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

2022-01-07 00:00:00 php yii2 gii

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

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

推荐答案

Active Query 表示与 Active Record 类关联的数据库查询.它通常用于覆盖特定模型的默认 find() 方法,它将用于在发送到 DB 之前生成查询:

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]);
     }

}

如果您之前使用过 Yii 1,那么这将取代 Yii 1.x Yii2 中的命名范围.您所要做的就是覆盖 model 类中的 find() 方法以使用上面的 ActiveQuery 类:

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 appmodelsOrderQuery(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();

<小时>

上面定义的相同 ActiveQuery 类的不同用例是在相关的模型类中定义关系数据时使用它,例如:


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 yiidbActiveRecord
{
    ...

    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(); 

相关文章