Yii2:ActiveQuery示例,为什么在Gii中单独生成ActiveQuery类? [英] Yii2 : ActiveQuery Example and what is the reason to generate ActiveQuery class separately in Gii?

查看:438
本文介绍了Yii2:ActiveQuery示例,为什么在Gii中单独生成ActiveQuery类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否提供示例用法.描述将是高度赞赏的.我找不到很好的例子.

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

推荐答案

活动查询表示与活动记录类关联的数据库查询.通常用于覆盖特定模型的默认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 \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();


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


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

这篇关于Yii2:ActiveQuery示例,为什么在Gii中单独生成ActiveQuery类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆